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
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
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.
coreyward
source share