在gem中扩展rails模型

时间:2013-06-20 09:21:16

标签: ruby-on-rails rubygems

我想扩展我的rails应用中定义的模型调用配置。出于某些建筑原因,如果我可以在宝石中扩展它将会很棒。

但是在我的gem foo.rb文件中,如果我调用我的配置类:

Configuration.class_eval do ... end

它给我这个错误:

configuration: undefined method 'config' for nil:NilClass (NoMethodError)

如果我试过这个:

class Configuration
  TEST = [:foo, :foo2].freeze
end

我无法访问我的rails应用程序中定义的activerecord类。

有没有办法重载gem中的某些rails类?

编辑: 像这样的工作:)

module m
  module ConfigurationExtension

    extend ActiveSupport::Concern

    included do
      CONSTAZ = [:foo].freeze
    end

    module ClassMethods
      def foo1
        "foo1"
      end
    end

    module InstanceMethods
      def foo2
        "foo2"
      end
    end
  end
end

require 'm/mailtie.rb' if defined?(Rails)

在我的铁丝文件中     模块       class mRailtie< ::导轨:: Railtie         config.after_initialize do           :: Configuration.send(:include,ConfigurationExtension)         结束       结束     端

1 个答案:

答案 0 :(得分:1)

假设您使用宝石的地方会有特定的类,这是非常错误的。相反,您应该在gem中创建一个模块,并在您想要的模型中包含/扩展/关注它(在这种情况下为Configuration