Can anyone explain this snipped of code from factory_girl

15 views
Skip to first unread message

adam

unread,
Jan 16, 2012, 5:02:59 AM1/16/12
to factory_girl
Ive seen the use of the method tap in a couple of spots in the source
code but can't figure out the need to use it. I know it's usually used
when you want to run some code within a long chain of calls ( usually
debugging ) but dont think thats what the reason is here.


#factory.rb

def attributes
compile
AttributeList.new(@name).tap do |list|
processing_order.each do |factory|
list.apply_attributes factory.attributes
end
end
end

and once again in #EvaluatorClassDefiner

def evaluator_class
@evaluator_class ||= Class.new(@parent_class).tap do |klass|
klass.callbacks ||= []
klass.callbacks += @callbacks
klass.attribute_lists ||= []
klass.attribute_lists += [@attributes]
end
end

Duncan Beevers

unread,
Jan 16, 2012, 11:00:46 AM1/16/12
to factor...@googlegroups.com
Object#tap is used to preserve the return value of the tapped function. Here's the first example, rewritten without tap.

def attributes
  compile
  list = AttributeList.new(@name)
  processing_order.each do |factory|
    list.apply_attributes factory.attributes
  end
  list
end

In both forms of this function the final value of `list` has to be returned. By using `tap` we can avoid this and just rely on the return value of AttributeList.new while still doing something useful with the intermediate value of `list`.

Here's a quick write-up on the functionality in case this explanation wasn't clear.


- Duncan


--
Individuals over processes. Interactions over tools. Agile Rails training from thoughtbot, the makers of Clearance, Shoulda, & Factory Girl:
http://thoughtbot.com/services/training

You received this message because you are subscribed to the "factory_girl" mailing list.
To post to this group, send email to factor...@googlegroups.com
To unsubscribe from this group, send email to
factory_girl...@googlegroups.com
For more options, visit this group at
http://groups.google.com/group/factory_girl?hl=en

Dan Tripp

unread,
Jan 16, 2012, 11:06:05 AM1/16/12
to factor...@googlegroups.com
I thought this explanation was pretty concise/useful:

- Dan


Dan Tripp

unread,
Jan 16, 2012, 11:07:11 AM1/16/12
to factor...@googlegroups.com
+1
Reply all
Reply to author
Forward
0 new messages