0

So I'm creating an acts_as kind of gem, and inside the gem I want a reference to the class that is including the gem, to define methods using its name, like for example

class MyObject < ActiveRecord::Base
  acts_as_whatever
end

I want to define methods from the gem using that class's name

module LocalInstanceMethods
  define_method "other_#{something.name.underscore.pluralize}" do
  end
end

What am I supposed to put instead of this something so that I could create a method called other_my_objects?

PS: calling self references the module I'm inside which is something like

ActsAsWhatever::LocalInstanceMethods

And self.class is

Module
2
  • have you tried with self.class.name ?
    – fanta
    Feb 27, 2015 at 19:04
  • yea, it returns the class name of the module, which is Module, I just added that to the question Feb 27, 2015 at 19:04

2 Answers 2

0

In your module, you need an included implementation.

module LocalInstanceMethods
  def self.included(other)
    class << other
     define_method "other_#{self.class.name.underscore.pluralize}" do
       # ...
     end
    end
  end
end

This code will execute with other being the module that this module is mixed into when it is included on the most module. You then open that class and define method on it rather than defining the method on the module and mixing that method into the host module.

2
  • I think it's kinda working, but it gave me sort of a singleton class, self.name is nil, and self.class is class, self is #<Class:Whatever(id: integer ...) rather than just Whatever(id: .. ) Feb 27, 2015 at 19:53
  • Whoops, yeah, you want self.class.name in there. Feb 27, 2015 at 20:31
0

Ok I figured this out, @ChrisHeald's answer was close to correct, but a small detail was messing this up, here's what worked for me

module LocalInstanceMethods
  def self.included(klass)
    define_method "other_#{klass.name.underscore.pluralize}" do
    end
  end
end

The part class < klass was messing up the self and klass variables together, without it now klass is the actual Model that I want, so klass.name returns the string I wanted for my method to be defined.

Also took me a while to notice that this it was def self.included not an included do block, that part was messing up all my tests.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.