【问题标题】:Extend a rails model in a gem在 gem 中扩展 rails 模型
【发布时间】:2013-06-17 02:11:16
【问题描述】:

我想扩展在我的 rails 应用程序中定义的模型调用配置。出于某种架构上的原因,如果我可以在 gem 中扩展它,那就太好了。

但是在我的 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)

在我的 railtie 文件中 模块 m 类 mRailtie

【问题讨论】:

    标签: ruby-on-rails rubygems


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-30
      • 2014-08-30
      • 2013-07-27
      • 2016-09-06
      • 1970-01-01
      • 1970-01-01
      • 2012-07-04
      相关资源
      最近更新 更多