Skip to content

Instantly share code, notes, and snippets.

@jamesbrooks
Last active December 14, 2015 19:58
Show Gist options
  • Save jamesbrooks/5140231 to your computer and use it in GitHub Desktop.
Save jamesbrooks/5140231 to your computer and use it in GitHub Desktop.
Block-based object constructor
class TeamBuilder
attr_accessor :name
attr_accessor :members
def initialize(name)
self.name = name
self.members = []
end
def player(name)
members << name
end
def self.create_team(name)
team = TeamBuilder.new(name) # or better yet, use Object#tap here!
yield team
team
end
end
TeamBuilder.create_team 'Awesome Team' do |t|
t.player 'Adam'
t.player 'Barry'
end
=> #<TeamBuilder:0x007f89721d3b40 @name="Awesome Team", @members=["Adam", "Barry"]>
@jamesbrooks
Copy link
Author

Here's the improved version of #create_team using Object#tap

def self.create_team(name)
  TeamBuilder.new(name).tap do |team|
    yield team
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment