1

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?

4

2 回答 2

1

而不是Client.dupuse Class.new(Client),它是 Client 的子类。

如果您想避免这种情况,这似乎适用于Client.dup

CA.send(:define_method, :some_method) do 
  puts "World"
end
于 2012-12-17T19:06:55.430 回答
1

如果你想用模块的数据覆盖特定的类,你想扩展它。

client = Client.new
client.extend(ClientA)
client.some_method
=> "World"

你可以在这里看到它的工作原理:http ://rubyfiddle.com/riddles/7621e

于 2012-12-17T19:09:43.130 回答