I’m reading through Avdi’s objects on rails book and don’t understand a section of sample code.
He creates a class like so I guess for dependency injection purposes:
class Blog
# ...
attr_writer :post_source
# ...
private
def post_source
@post_source ||= Post.public_method(:new)
end
end
Then he writes the following spec
# spec/models/blog_spec.rb
require 'ostruct'
describe Blog do
# ...
describe "#new_post" do
before do
@new_post = OpenStruct.new
@it.post_source = ->{ @new_post }
end
it "returns a new post" do
@it.new_post.must_equal @new_post
end
it "sets the post's blog reference to itself" do
@it.new_post.blog.must_equal(@it)
end
end
end
I don’t understand why he uses @it.post_source = ->{ @new_post }
Why didn’t he just use something like @it.post_source = OpenStruct.public_method(:new) which would be similar to his Blog class code which has @post_source ||= Post.public_method(:new)
Is there a reason for this?
->{ @new_post }is a lambda that returns the instance stored in @new_post.Post.public_method(:new)would return the constructor method of PostPassing in the lambda for the class to use lets you have control of the instance that is returned. Passing in a class’ constructor means you don’t know what instance it will get, just that it will be of the class you specified.