Topic: Modules/Mixins and self for accessing the calling object?

Hello there,

I am stuck at a problem regarding modules here. I have a module that's included in my model and I need to get to know the class name of my model from within the module. Problem is, that "self" is always pointing to the module class (at least I think so) and I do not know how to access the calling object.

Here's the code:

module ActiveRecord
  module Acts
    module AclControlled
      def self.included(base)
        base.send :extend, InstanceMethods
        base.send :extend, ClassMethods
      end
      
      module InstanceMethods
        def controlled_object
          Rails.logger.info "Fetching ControlledObject..."
          controlled_object = ControlledObject.find(:first, :conditions => {:model => self.class.to_s, :model_id => self.id })
        end
      end
      
      [...]
    end
  end
end

Does anyone know how to get access to the calling object here?

Thanks in advance

Arne

Re: Modules/Mixins and self for accessing the calling object?

in irb - here's a simple inclusion of a module in a class.  In this case, the instance can get it's class ok.

>> module MyModule
>>   def get_class_name
>>     self.class.name
>>   end
>> end
=> nil
>>
?> class MyClass
>>   include MyModule
>> end
=> MyClass
>>
?> my_object = MyClass.new
=> #<MyClass:0xb74f43d8>
>> my_object.get_class_name
=> "MyClass"

So, maybe the difference is how you're mixing the module into the class?

I think that in this case you're mixing both sets of methods (instance methods and class methods) in at the class level:

      def self.included(base)
        base.send :extend, InstanceMethods
        base.send :extend, ClassMethods
      end


Try this instead

      def self.included(base)
        base.send :include, InstanceMethods
        base.send :extend, ClassMethods
      end

###########################################
#If i've helped you then please recommend me at Working With Rails:
#http://www.workingwithrails.com/person/ … i-williams

Re: Modules/Mixins and self for accessing the calling object?

Hi Max,

you're right, this and another fault of mine had been the issue here. The mixin is now working as supposed. Thanks for your help again!