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

北城以北 提交于 2019-12-25 05:25:30

问题


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


来源:https://stackoverflow.com/questions/13052427/how-to-define-a-method-from-a-gem-to-use-within-a-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!