Reputation: 7855
I have a model called Client
and I would like to clone it in certain cases where clients (the real world kind) have modifications that require class level changes.
For example, if I have:
class Client
set_table_name :clients
def some_method
puts "Hello"
end
end
Then if I have the following:
module ClientA
def some_method
puts "World"
end
end
I would expect that I could clone (or dup) the class, then include the module to overwrite the method some_method
.
But here's what happens in my production console:
> CA = Client.dup
> CA.singleton_class.send(:include, ClientA) # Or just CA.send(:include, ClientA)
> client = CA.new
> client.some_method
=> "Hello" # Expected "World"
Is there a trick to this?
Upvotes: 1
Views: 497
Reputation: 7586
Instead of Client.dup
use Class.new(Client)
, which subclasses Client.
If you're trying to avoid that, this seems to work with Client.dup
:
CA.send(:define_method, :some_method) do
puts "World"
end
Upvotes: 1
Reputation: 40277
If you're wanting to override specific classes with a module's data, you want to extend it.
client = Client.new
client.extend(ClientA)
client.some_method
=> "World"
You can see it work here: http://rubyfiddle.com/riddles/7621e
Upvotes: 1