How to define a method from a gem to use within a

2019-09-07 07:38发布

问题:

I'm trying to build a gem and I want to define a method my_method inside the gem and use it inside a model.

Example:

class MyModel < ActiveRecord::Base
    my_method
end

My gem:

#lib/my_gem.rb
require "my_gem/model_inclusions"
module MyGem

end

#lib/my_gem/model_inclusions.rb
module MyGem
  def self.included(base)
    base.extend ClassMethods
  end

  module ClassMethods
    def my_method

    end

  end
end

When I try the example it gives me undefined method 'my_method' for <Class:0x00000045434> (NoMethodError)

回答1:

module NumberInternationalizer
 def my_method
  ...
 end

end

ActiveRecord::Base.send :extend, NumberInternationalizer