7
\$\begingroup\$

I have a set of Class methods which is :

class << self
def increment_value
 self.first.increment_value
end
def max_work_hours_per_day
 self.first.max_work_hours_per_day
end
def fast_completion_day
 self.first.fast_completion_day
end
def super_fast_completion_day
 self.first.super_fast_completion_day
end
def ludicrous_completion_day
 self.first.ludicrous_completion_day
end
def budget_completion_day
 self.first.budget_completion_day
end
end

Since all the methods call self.first.atttibute where attribute is the same name as function name. I think we can reduce this to a single method. Something like method_missing is there in Ruby , but since I am not very good at meta programming , I am seeking advise here.

asked Aug 20, 2011 at 3:16
\$\endgroup\$
1
  • 1
    \$\begingroup\$ This and this look like reasonabl nice ways to handle delegation in Ruby. \$\endgroup\$ Commented Aug 20, 2011 at 4:38

1 Answer 1

13
+50
\$\begingroup\$

Ruby already has a module which allows you to forward specific methods to a given object in its standard library: the Forwardable module.

Using it you can write code like this:

class << self
 extend Forwardable
 def_delegators :first, :increment_value, :max_work_hours_per_day #...
end

I think spelling out the methods you want to forward like this is preferable to simply forwarding everything as it won't accidentally forward something you don't want to forward. It also does not affect the error message when calling a method that does not exist.

answered Aug 23, 2011 at 10:24
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.