dynamically created functions?

L

Lin Wj

def self.developer_options(*args)
fetch_options({'area'=>'developers','index' => args.first})
end

def self.priority_options(*args)
fetch_options({'area'=>'priority','index' => args.first})
end

def self.status_options(*args)
fetch_options({'area'=>'status','index' => args.first})
end

is there anyway to dynamically create methods with a specific name ?

ie: create methods which are

def self.??????_options(*args)
fetch_options({'area'=>'?????','index' => args.first})
end
 
R

Ralf Mueller

Lin said:
def self.developer_options(*args)
fetch_options({'area'=>'developers','index' => args.first})
end

def self.priority_options(*args)
fetch_options({'area'=>'priority','index' => args.first})
end

def self.status_options(*args)
fetch_options({'area'=>'status','index' => args.first})
end

is there anyway to dynamically create methods with a specific name ?

ie: create methods which are

def self.??????_options(*args)
fetch_options({'area'=>'?????','index' => args.first})
end
see http://www.ruby-doc.org/core-1.8.7/classes/Module.html#M000396

regards
ralf
 
J

Jesús Gabriel y Galán

=A0def self.developer_options(*args)
=A0 =A0fetch_options({'area'=3D>'developers','index' =3D> args.first})
=A0end

=A0def self.priority_options(*args)
=A0 =A0fetch_options({'area'=3D>'priority','index' =3D> args.first})
=A0end

=A0def self.status_options(*args)
=A0 =A0fetch_options({'area'=3D>'status','index' =3D> args.first})
=A0end

is there anyway to dynamically create methods with a specific name ?

ie: create methods which are

def self.??????_options(*args)
=A0 =A0fetch_options({'area'=3D>'?????','index' =3D> args.first})
=A0end

As Ralf said, you can use define_method. If you want to create them
up-front (untested):

%w{developer priority status}.each do |area|
define_method "#{area}_options" do |*args|
fetch_options({'area' =3D> area, 'index' =3D> args.first})
end
end

Of course this needs to be done in the scope where self is the
singleton class of the object (see a recent post about this).

If you want to define them lazily, you can use method_missing (untested):

def method_missing (meth, *args, &blk)
m =3D meth.match /(.*)_options$/
super unless m
define_method meth do |*arguments|
fetch_options({'area' =3D> m[1], 'index' =3D> arguments.first})
end
end

Hope this helps,

Jesus.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,779
Messages
2,569,606
Members
45,239
Latest member
Alex Young

Latest Threads

Top