How to define method with variables in arg 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

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.

thanks, Brian.

That’s a great solution.
It works.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs