Simple act_as template

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 : textsnippets.com

Gaspard B.

Any chance of quick guide to how all that works?

Thank you! That’s exactly the explanation I was looking for but haven’t
found anywhere in any tutorials!

Charlie B. 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