在宝石中扩展导轨模型 [英] Extend a rails model in a gem

查看:71
本文介绍了在宝石中扩展导轨模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想扩展在我的Rails应用程序中定义的模型调用配置。因为一些体系结构的原因,如果我可以将它扩展到宝石中,它会很好。



但是在我的gem foo.rb文件中,如果我打电话给我的配置类:

  Configuration.class_eval do ... end 

它返回给我这个错误:

配置:未定义方法'config'为nil:NilClass(NoMethodError)



如果我试过:

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





有没有办法在gem中重载一些rails class?



编辑:
类似这样的工作:)

  module m 
模块ConfigurationExtension

扩展ActiveSupport ::关注

包含做
CONSTAZ = [:foo] .freeze
结束

模块ClassMethods
def foo1
foo1
结束
结束

模块InstanceMethods
def foo2
foo2
结束
结束
结束
结束

如果定义了需要'm / mailtie.rb'?(Rails)

在我的railtie文件中
模块m
class mRailtie< :: Rails :: Railtie
config.after_initialize do
:: Configuration.send(:include,ConfigurationExtension)
end
end
end

解决方案

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


I wanted to extend a model call Configuration defined in my rails app. 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:

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.

Is there a way to overload some rails classes in a gem?

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

解决方案

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)

这篇关于在宝石中扩展导轨模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆