Acts_as_taggable magic.... please explain


#1

Hi,

There is a line in acts_as_taggable plugin:
send(acts_as_taggable_options[:from]).tags.find_or_create_by_name(name).on(self)

could someone explain what is:
send(xxx)
and
.on(self)

I cannot find it rDoc


#2

Hi,

send(acts_as_taggable_options[:from]).tags.find_or_create_by_name(name).on(self)
could someone explain what is:
send(xxx)

“Send” sends a message to an object.
So |"|Wiktor Schmidt|".send(:length) if equivalent to “|Wiktor
Schmidt|”.||length

In the case below, the :from option lets you |attribute the tag to
another object.

Class Photo
acts_as_taggable :from => :current_user
end

So the code above that you were asking about will then call
Photo.current_user.tags.find … instead of Photo.tags.find …
Check out this chapter in the Pickaxe for some more info on send.
http://www.rubycentral.com/book/ospace.html

.on(self)
The on method is part of acts as taggable. You can find it in tag.rb

def on(taggable)
taggings.create :taggable => taggable
end

So if we simply it a bit:

#With the current user, find or create a tag called “mynewtag” and
associate it with Photo
#Actual Code ->
send(acts_as_taggable_options[:from]).tags.find_or_create_by_name(name).on(self)
#Code with hardcoded values
Photo.current_user.tags.find_or_create_by_name(“mynewtag”).on(Photo)

You can check out this post on Rails Wheenie for some extra help.
http://rails.techno-weenie.net/question/2006/3/6/how_to_add_user_to_acts_as_taggable

Hopefully this helps out a bit.

Cheers,
Eric G.


Eric G.
http://www.ericgoodwin.com


#3

“send” is a method available on all objects you can use to call an
arbitrary method. object.send(:method, param) in Ruby is like object
‘method’ in Javascript.

Used in this context, acts_as_taggable_options[:from] contains a
symbol for an association that responds to :tags. This returns the
an association proxy of tags for that object, limiting the tags you
create to a given tag space.

‘find_or_create_by_name’ will call the class method delegated from
the ‘tags’ association. This returns a single Tag instance.

‘on’ is a method on the Tag instance that will create the join model
to make the association between your model and the new/reused tag.

This roundabout way of creating the join model is needed because of
the polymorphic association. For an explanation, take a look at:
http://blog.hasmanythrough.com/articles/2006/04/17/join-models-not-
proxy-collections

HTH,
Sean