Reputation: 5916
Is it possible in Ruby to delegate to a class method of another class so to replace the method below?
def sugar(param)
Klass.a_very_long_method_name(param)
end
I have tried to use Forwardable
extend Forwardable
def_delegator 'Klass.a_very_long_method_name', :sugar
But it doesn't seem to work.
I find myself to call Klass.a_very_long_method_name
in many places and I'm trying to dry things up.
Upvotes: 4
Views: 84
Reputation: 110665
require 'forwardable'
class Klass
def self.a_very_long_method_name(name)
puts "Hi, #{name}"
end
end
class Sugar
extend Forwardable
def_delegator Klass, :a_very_long_method_name, :verrry_long
end
s = Sugar.new
s.verrry_long "Sue"
# Hi, Sue
In def_delegator Klass, :a_very_long_method_name, :verrry_long
, Klass
is the receiver of the message forwarding, :a_very_long_method_name
is the message to be forwarded and :verrry_long
is an alias of the message :a_very_long_method_name
.
Upvotes: 5