Tom
Tom

Reputation: 2085

Struggling to understand how this block works

I am looking at factories in rails and have hit a problem in my understanding of this code:

Factory.define :user do |f|
  f.username "foo"
  f.password "foobar"
  f.password_confirmation { |u| u.password }
end

I understand the mechanics of everything except for

f.password_confirmation { |u| u.password }

How would this know to assign "foobar" to f.password_confirmation in the case where I used "foobar" as a custom password. Or in other words what does 'u' reference. Thanks in advance.

Upvotes: 0

Views: 66

Answers (1)

Joe Ferris
Joe Ferris

Reputation: 2732

The "u" in that case actually represents an "Evaluator" class, which is an internal proxy used by factory_girl. It's a dynamically defined class that responds to methods for the attributes you're defining on your factory.

The Evaluator allows you to access previously defined attribute values, and it will generate, cache, and return the correct value if the attributes are out of order. For example, swapping the order of "password" and "password_confirmation" will still work because of the way the Evaluator works.

You can see how Evaluator works here: https://github.com/thoughtbot/factory_girl/blob/master/lib/factory_girl/evaluator.rb

You mostly don't need to worry about the Evaluator when defining factories. You can generally "u" there like it's an instance of a User, because it will delegate missing methods to the instance that it's building.

Upvotes: 2

Related Questions