The standard Ruby reflection does not provide for getting method parameter names (at least afaik), and the only other solution that I found is using parsetree, which is “more clean” then this method, but requires another gem…
So here it comes Monkey-Style:
def methods_with_parameters(klass, path_to_file) methods = klass.instance_methods(false).sort lines = File.read(path_to_file) #find params for methods methods.map do |method| lines.detect{|l|l=~/def #{method}(.*)$/} parameters = $1.tr('()','').split(',').map{|p| p.gsub(/=.*/, '')}.reject(&:blank?).map(&:strip) [method, parameters] end end
multiline args?
boom
yep, your right, it would only find the one on the first line, its not failsafe just a monkeypatch… *works-on-my-codebase*-approved 😉
I had the same need and I solved using RubyParser in a very simple gem that provides named parameters for any method:
http://github.com/maca/arguments
Kudos, Ryan 🙂
hmm i dont see how this would give me the parameter names of e.g. def xxx(hello, foo=nil, bar=1) –> [‘hello’,’foo’, ‘bar’]