DelegateClass vs Class Inheritance in Ruby

Can someone comment on when to use delegation via DelegateClass (e.g. Seller < DelegateClass(Person) ) and when to use class inheritance (e.g. Seller < Person ) in ruby?

 class Seller < DelegateClass(Person) def sales ... end end class Seller < Person def sales ... end end 

When I looked at the Ruby on Rails source on Github, I found quite a bit of using DelegateClass .

+7
inheritance ruby delegation
source share
2 answers

There are several differences that can help you understand which approach to use.

1) You can safely delegate primitives (for example, String), but you can not always reliably inherit from them

If you build on top of Hash or String or Fixnum , you can safely use a DelegateClass (or another delegate). More on why, Steve Klabnik warns , this is a good place to start).

2) DelegateClass simplifies the "conversion" of a more general object to a more specific

This makes it easy to receive an instance of a shared object and leads it to what matches your implementation:

 class Message < DelegateClass(String) def print upcase end end # […] def log(message) message = Message.new(message) unless message.is_a?(Message) end 

3) Subclasses of getcha: DelegateClass expect the instance of the delegated class to be the argument new

This can make it difficult to use the subclass classes that you pass to the library code. For example, this is a fairly common practice that will not work out of the box using DelegateClass :

 class MyLogger < DelegateClass(ActiveSupport::Logger); end Foo::ThirdParty::Library.configure do |c| c.logger = MyLogger # no good end 

This does not work, because our library will behave like most registrars and create instances without arguments. This can be solved by specifying initialize and creating an instance of ActiveSupport::Logger , but probably not the right solution in this case.

+5
source share

delegates model different types of Person behavior based on context. for example, the same person may be a seller in one context or a buyer in another context. Inheritance is tougher: a Bear and Tiger inherit from Animal , but an instance of Animal should never sometimes behave like a Bear and sometimes behave like a Tiger . An instance of an Animal descendant is either one or the other.

0
source share

All Articles