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

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

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 )

Facebook photo

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

Connecting to %s