I can't figure out the proper block initialize
class Foo
attr_accessor :bar
end
obj = Foo.new do |a|
a.bar = "baz"
end
puts obj.bar
Expect "baz" instead get nil
What is the proper incantation for block class initializers in ruby?
Another way to make a block initializer would be writing it yourself one:
class Foo
attr_accessor :bar
def initialize
yield self if block_given?
end
end
And later use it:
foo = Foo.new do |f|
f.bar = true
end
My two cents.
Try again:
class Foo
attr_accessor :bar
end
obj = Foo.new.tap do |a|
a.bar = "baz"
end
puts obj.bar
NameError.yield self if block_given? in the Foo's initialize method, because often you can't or don't want to modify the Foo class (think of the Open Closed Principle). Plus, why clutter up the initialize method of the Foo class, when a simple method chaining of tap would do?I don't think Never saw it anywhere anyway. Why do you want to initialize in a block ? You can always do new can take a block.obj = foo.new.tap do |a| ... If you really want a block
actually you have a constructor for these purposes:
class Foo
attr_accessor :bar
def initialize(bar = "baz")
@bar = bar
end
end
attr_accessorcan't work in that form and the block is never called.FactoryGirlwhere this would be of advantage?