Forum: Ruby how to define method with variables in arg list

Posted by salamond (Guest)
on 2012-11-12 09:15
(Received via mailing list)
Hi, all.

I'm re-factoring code. with some duplicated code like:

Class Gui
def add_user(name, age, sex, location)
  @agent.post(url + '/user', {'name'=>name, 'age'=>age, 'sex'=>sex,
'location'=>location})
end

def add_class(name, floor, room_number)
  @agent.post(url + '/classroom', {'name' => name, 'floor'=>floor,
'room_number'=>room_number})
end
end

Agent will format this into an html get/post request.

I want to do this in a rails format.
e.g.
class Gui < Base
  method :add_user, :name, :age, :sex, :location
  method :add_class, :name, :floor, :room_number
end

class Base
  class << self
    def method(method_name, *args)
      define_method(method_name) |*args| # problem is here. how can I
define a method, with dynamic numbers of variables?
      end
    end
  end
end


thanks

Jaordzz
Posted by Brian Candler (candlerb)
on 2012-11-12 16:22
salamond wrote in post #1084048:
>       define_method(method_name) |*args| # problem is here. how can I
> define a method, with dynamic numbers of variables?

I think class_eval %Q{def method(#{args.join(",")}) ... end} is your 
best bet.
Posted by salamond (Guest)
on 2012-11-13 03:17
(Received via mailing list)
thanks, Brian.

That's a great solution.
It works.
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.