Skip to content

Instantly share code, notes, and snippets.

@ryosuke-endo
Created October 11, 2016 11:00
Show Gist options
  • Save ryosuke-endo/e62e1dfc50fd65ed77a4241b37105a18 to your computer and use it in GitHub Desktop.
Save ryosuke-endo/e62e1dfc50fd65ed77a4241b37105a18 to your computer and use it in GitHub Desktop.
class Family
def self.build
yield
end
end
x = Family.build do |family|
family.new_child('john') do |child|
child.hobby = 'game'
child.age = 18
end
family.new_child('yamada') do |child|
child.hobby = 'study'
child.age = 12
end
end
x.children
@ryosuke-endo
Copy link
Author

ryosuke-endo commented Oct 11, 2016

修正

class Family
  attr_reader :children

  def initialize
    @children = []
  end

  def new_child(name)
    child = Child.new(name)
    @children << Child.new(name)
    child
  end
end

class Child
  attr_writer :hobby, :age

  def initialize(name)
    @name = name
  end
end

@ryosuke-endo
Copy link
Author

やり直した

class Family
  attr_reader :children

  class << self
    def build
      family = self.new
      yield(family)
      family
    end
  end

  def initialize
    @children = []
  end

  def new_child(name)
    child = Child.new
    yield(child)
    @children << child
  end
end

class Child
  attr_writer :hobby, :age
end

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