Ruby Monkey-Reflection to get Method Parameter Names

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
Advertisements

5 thoughts on “Ruby Monkey-Reflection to get Method Parameter Names

  1. yep, your right, it would only find the one on the first line, its not failsafe just a monkeypatch… *works-on-my-codebase*-approved πŸ˜‰

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s