Extend a rails model in a gem

2019-06-02 07:46发布

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

1条回答
forever°为你锁心
2楼-- · 2019-06-02 08:23

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)

查看更多
登录 后发表回答