Search code examples
rubyclassclone

How to make Class.clone or Class.dup work in ruby?


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?


Solution

  • 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