当前位置: 动力学知识库 > 问答 > 编程问答 >

ruby - redefining gem method in rails model not working

问题描述:

So I have a gem that contains some activerecord models that gets used by multiple applications on our platform. We had a constant defining a list of "types" that was divergent on a couple different applications.

# in the gem

class MyModel < ActiveRecord::Base

TYPES = ["A Type", "Another Type"]

end

Redefining this constant in the application code will generate a warning for an already initalized constant. So since it's not really constant, I decided to refactor it to a class method.

# gem

class MyModel < ActiveRecord::Base

def self.types

[]

end

end

# application a

class MyModel < ActiveRecord::Base

def self.types

["A Type", "D Type"]

end

end

# application b

class MyModel < ActiveRecord::Base

def self.types

["B Type", "C Type"]

end

end

However, when accessing MyModel.types in App A or B, types is []. This, and a few other issues, have lead me to conclude that the gem is loaded after the rails app is loaded, while my assumption was the opposite.

what would be the best way to handle a divergent case such as this?

网友答案:

Do this in your applications

Create a file in your config/initializers/ and add this code in both your apps

MyModel.instance_eval do
  def types
    ["A Type", "D Type"]
  end
end

or

MyModel.class_eval do
  def self.types
    ["A Type", "D Type"]
  end
end
网友答案:

You must require the initial class explicitly from your engine, this will ensure it is loaded. Which is sometimes not the case in development (autoload for instance)

require YourEngine::Engine.root.join('app/models/your_namespace/my_model')

class MyModel  #no inheritance here, we just reopen an existing class, right?
   def self.types
     [] #override it as you like
   end
end
分享给朋友:
您可能感兴趣的文章:
随机阅读: