Search code examples
rubydelegation

How do you delegate class methods?


I would like to make a class which delegates all instance and class methods to another class. My aim is to be able to give a class which is set in the app options a name which appears to fit in with the code around it.

This is what I have so far:

require 'delegate'

class Page < DelegateClass(PageAdapter)
  # Empty
end

However, this only seems to delegate instance methods, not class methods.


Solution

  • You don't want delegation, you want direct subclassing:

    class Page < PageAdapter
      # Empty
    end
    

    Proof:

    class Foo
      def self.cats?
        "YES"
      end
      def armadillos?
        "MAYBE"
      end
    end
    
    class Bar < Foo; end
    
    p Bar.new.armadillos?
    #=> "MAYBE"
    
    p Bar.cats?
    #=> "YES"