Ruby Forum Ruby on Rails > Simple act_as template

Posted by Gazoduc (Guest)
on 10.04.2006 13:57
Hello !

I posted a simple template to show how to add 'act_as_whatever' to 
ActiveRecord.
I think this might be useful to others as there are some trickery ruby 
things in this
file.

Here is the template : http://textsnippets.com/posts/show/384

Gaspard Bucher
Posted by Charlie Bowman (Guest)
on 10.04.2006 14:39
(Received via mailing list)
Any chance of quick guide to how all that works?
Posted by Gazoduc (Guest)
on 10.04.2006 15:12
Charlie Bowman wrote:
> Any chance of quick guide to how all that works?

The beggining is just to set a namespace :
module YourSuperName
  module Acts
    module Idiot

Then there is a module method that we overwrite. This method is called 
when the module is included
into another object ('base' here as it will be ActiveRecord::Base)  :
      def self.included(base)
        # add all methods from the module "AddActsAsMethod" to the 
'base' module
        base.extend AddActsAsMethod
      end

So we extend the base object with our 'acts_as_idiot' method. This adds
'acts_as_idiot' to the class methods of ActiveRecord::Base.

Then we have the 'acts_as_idiot' method itself :
        def acts_as_idiot
          # BELONGS_TO HAS_MANY GOES HERE

          class_eval <<-END
            include YourSuperName::Acts::Idiot::InstanceMethods
          END
        end

This method makes the following lines
    class Myobj < ActiveRecord::Base
       acts_as_idiot
    end

behave like
    class Myobj < ActiveRecord::Base
       include YourSuperName::Acts::Idiot::InstanceMethods
    end

And the last tricky part :

      module InstanceMethods
        def self.included(aClass)
          aClass.extend ClassMethods
        end

This is executed when the instance methods are added to the class. 
'Self' here is the Myobj class, so
extending it with aClass.extend moduleName will add the methods in the 
module to the class instead
of the object.

The very last line
    ActiveRecord::Base.send :include, YourSuperName::Acts::Idiot

is equivalent to
    class ActiveRecord::Base
      include YourSuperName::Acts::Idiot
    end

This effectively includes our code into ActiveRecord, making 
'acts_as_idiot' available as a class method.

I hope these explanations made it clearer...

Gaspard
Posted by Charlie Bowman (Guest)
on 11.04.2006 14:33
(Received via mailing list)
Thank you!  That's exactly the explanation I was looking for but haven't
found anywhere in any tutorials!