For example, in FactoryGirl, it allows you to do something like
factory :user, :class => User do
sequence :username do |n|
"blahblah#{n}"
end
end
I’ve looked through the source code at https://github.com/thoughtbot/factory_girl but can’t seem to figure out how they are achieving this (it loks like it’s some type of proxy?). That is, how is it we are able to access the sequence method?
They are using instance_eval.
This means that inside the block
self(and thus the objectsequenceis called on) isn’t what it would otherwise be (probably the top level object in this case) but the object thatinstance_evalwas called on (in this case an object that implements the constructs of the factory girl syntax.It’s often used with DSLs (another example is the routes.rb file in rails >= 3) because without it you’d have to do something like
which tend to distract from the DSL.
One tiny example illustrating its effects
With a ‘normal’ block this would have raised an error, because the top level object has no
lengthmethod, but becauseinstance_evalis used length is called on the string instead.