简体   繁体   中英

Accessing other methods in a Ruby module

I am writing my first Rails gem, which adds a method to ActiveRecord. I can't seem to figure out a simple way to call other methods from within the method I am adding to ActiveRecord. Is there a pattern for this I should be using?

module MyModule

  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods

    def my_class_method
      # This doesn't work
      some_utility_method
    end

  end

  def some_utility_method
    # Do something useful
  end

end

ActiveRecord::Base.send(:include, MyModule)

Once you've included MyModule , ActiveRecord::Base will have my_class_method as a class method (equivalently, an instance method of the Class object ActiveRecord::Base ), and some_utility_method as an instance method.

So, inside my_class_method , self is the Class ActiveRecord::Base , not an instance of that class; it does not have some_utility_method as an available method

Edit: If you want a utility method private to the Module, you could do it like this:

module MyModule

  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods

    def my_class_method
      # This doesn't work
      MyModule::some_utility_method
    end

  end

  def self.some_utility_method
    # Do something useful
  end

end

ActiveRecord::Base.send(:include, MyModule)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM