Reputation: 2365
I have two Rails projects, we'll call them Foo and Bar. They share the same models. The models live in Foo and Bar links to those files.
The behavior of a particular method in one of Foo's models needs to be different in Bar:
In project Foo's models/model_a.rb:
class ModelA
def method_a
puts "default behavior here"
end
end
Somewhere in project Bar:
class ModelA
def method_a
puts "special behavior here"
end
end
so that the following line of code:
x = model_a.method_a
would execute differently in one project than in the other without Bar having to mess with Foo's models. A similar situation would exist, presumably, if Foo's models were simply a gem, although the load-order question would be different.
My questions are: where should this code snippet live in project Bar? And how do I guarantee that Bar's mix-in is loaded last so that the correct function executes at runtime in project Bar?
Upvotes: 0
Views: 665
Reputation: 2380
Inheritance? That's what you're describing.
If this is Active Record, then you can force the table name in the Bar app and then use the child class there.
Alternatively, but I think this is a hack. Create an initializer called override_model_a
require 'modelA'
class ModelA
# then do your initializing, or include your module here
end
Ruby does "last one wins" so if you require the original class and then override it in the initializer it will do what you want.
Upvotes: 2