Forum: Ruby on Rails Simple act_as template

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
Gazoduc (Guest)
on 2006-04-10 15:57
Hello !

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

Here is the template :

Gaspard B.
Charlie B. (Guest)
on 2006-04-10 16:39
(Received via mailing list)
Any chance of quick guide to how all that works?
Gazoduc (Guest)
on 2006-04-10 17:12
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

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

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

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

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

And the last tricky part :

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

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

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

I hope these explanations made it clearer...

Charlie B. (Guest)
on 2006-04-11 16:33
(Received via mailing list)
Thank you!  That's exactly the explanation I was looking for but haven't
found anywhere in any tutorials!
This topic is locked and can not be replied to.