James Nelson
James Nelson

Reputation: 43

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.

Upvotes: 3

Views: 1194

Answers (2)

Phrogz
Phrogz

Reputation: 303166

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"

Upvotes: 0

Linuxios
Linuxios

Reputation: 35783

You could define your own delegation scheme:

class Page < DelegateClass(PageAdapter)
  @@delegate_class=PageAdaptor
  def self.delegate_class_method(*names)
    names.each do |name| 
      define_method(name) do |*args|
        @@delegate_class.__send__(name, *args)
      end
    end
  end
  delegate_class_method @@delegate_class.singleton_methods
end

Upvotes: 2

Related Questions