Forum: Ruby on Rails acts_as_taggable magic.... please explain

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Wiktor -. (Guest)
on 2006-04-20 20:41
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
Eric G. (Guest)
on 2006-04-20 22:10
(Received via mailing list)
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/h...

Hopefully this helps out a bit.

Cheers,
Eric G.

--
Eric G.
http://www.ericgoodwin.com
Sean Treadway (Guest)
on 2006-04-20 22:35
(Received via mailing list)
"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'](param) 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...
proxy-collections

HTH,
Sean
This topic is locked and can not be replied to.