[英]Extend a rails model in a gem
I wanted to extend a model call Configuration defined in my rails app. 我想扩展在我的rails应用程序中定义的模型调用Configuration。 For some architectural reason, it will be great if i can extend it in a gem.
由于某种架构上的原因,如果我可以将其扩展成一个宝石,那将是很棒的。
But in my gem foo.rb file if i call my configuration class: 但是在我的gem foo.rb文件中,如果我调用配置类:
Configuration.class_eval do ... end
It return me this error: 返回此错误:
configuration: undefined method 'config' for nil:NilClass (NoMethodError)
And if i tried this : 如果我尝试过这个:
class Configuration
TEST = [:foo, :foo2].freeze
end
I cannot access anymore to my activerecord class defined in my rails app. 我无法再访问在我的rails应用程序中定义的activerecord类。
Is there a way to overload some rails classes in a gem? 有没有办法在gem中重载某些Rails类?
EDIT : Something like this work :) 编辑:像这样的工作:)
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)
In my railtie file module m class mRailtie < ::Rails::Railtie config.after_initialize do ::Configuration.send(:include, ConfigurationExtension) end end end 在我的铁路文件模块m类mRailtie <:: Rails :: Railtie config.after_initialize do :: Configuration.send(:include,ConfigurationExtension)结束结束结束
This is very wrong to assume that where you use your gem there will be specific class. 假设在使用宝石的地方会有特定的类别,这是非常错误的。 Instead you should create a module in a gem and include/extend/concern it in the model you want (
Configuration
in this case) 相反,您应该在gem中创建一个模块,并在所需模型中包含/扩展/关注它(在这种情况下为
Configuration
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.