[英]Extend a rails model in a gem
我想擴展在我的rails應用程序中定義的模型調用Configuration。 由於某種架構上的原因,如果我可以將其擴展成一個寶石,那將是很棒的。
但是在我的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)
在我的鐵路文件模塊m類mRailtie <:: Rails :: Railtie config.after_initialize do :: Configuration.send(:include,ConfigurationExtension)結束結束結束
假設在使用寶石的地方會有特定的類別,這是非常錯誤的。 相反,您應該在gem中創建一個模塊,並在所需模型中包含/擴展/關注它(在這種情況下為Configuration
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.