Ruby Reflection Method Parameters

S

Sirisha Pusapati

Hi,

I have a class called ClassFromString and it has a method called
getCounterValue. It takes a parameter called name. Is there in Ruby
using reflection to get the name of the parameters of a method.

class ClassFromString
@@counter = 0
def initialize
@@counter += 1
end

def getCounterValue(name)
puts name
end
end

def createClassFromString(classname)
ObjectSpace.each_object(Class) do |x|
if x.name == classname
object = x.new
for method in object.public_methods(false)=> Here I want to get the
parameters that are supported by the function
object.send(method,"Sirisha hi htere")
end
end

end
end
createClassFromString("ClassFromString")
 
P

Phrogz

I have a class called ClassFromString and it has a method called
getCounterValue. It takes a parameter called name. Is there in Ruby
using reflection to get the name of the parameters of a method.

There is not. The closest you can get is a hack that reads in source
files (if you know where they are, and they're pure Ruby) and either
parses the raw code or looks at the abstract syntax tree.

Though I'm not actually recommending that you use it, this is why I
wrote my own DescribeMethods module:
http://phrogz.net/RubyLibs/rdoc/files/DescribeMethods_rb.html
(Seriously way more work than you want to do, I'm sure.)
 
J

Jörg W Mittag

Phrogz said:
There is not.

<bill-clinton>That depends on what your definition of "is"
is.</bill-clinton>

You are wrong, in so far as Proc#parameters does exist in Ruby 1.9.2.
You are right, in so far as Ruby 1.9.2 doesn't exist (yet).

See: said:
The closest you can get is a hack that reads in source
files (if you know where they are, and they're pure Ruby

.... and they exist at all (i.e. the method was not created using eval
or define_method)
) and either
parses the raw code or looks at the abstract syntax tree.

Here is how the Merb-Action-Args Plugin for Merb does it:

JRuby: <https://GitHub.Com/WyCats/Merb/blob/master/merb-action-args/lib/merb-action-args/jruby_args.rb>
(using JRuby's own runtime reflection)

MRI: <https://GitHub.Com/WyCats/Merb/blob/master/merb-action-args/lib/merb-action-args/mri_args.rb>
(using ParseTree)

For all others, it tries to use the MethoPara Gem, which, however,
only works on YARV 1.9.1 (and *not* on Ruby 1.9.1, as the README
incorrectly claims!): <https://GitHub.Com/Genki/MethoPara/>

jwm
 

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,754
Messages
2,569,527
Members
45,000
Latest member
MurrayKeync

Latest Threads

Top