Project

General

Profile

Actions

Feature #8629

closed

Method#parameters should include the default value

Added by rosenfeld (Rodrigo Rosenfeld Rosas) almost 11 years ago. Updated almost 11 years ago.

Status:
Rejected
Target version:
-
[ruby-core:55976]

Description

def a_method arg1=1, now = Time.now, arg2 = arg1 + 1
end

method(:a_method).parameters == [[:opt, :arg1], [:opt, :now], [:opt, :arg2]]

I'd prefer if it could return [[:opt, :arg1, 1], [:opt, :now, now_proc], [:opt, :arg2, arg2_proc]], and expect now_proc[] to be the current time and arg2_proc[] to raise an exception since arg1 is not defined.

Rationale:

Ruby doesn't support optional typing such as:

def a_method Date date, Integer n = 0, String name = ''
end

Groovy does, and this allows Grails to perform some interesting stuff, like params binding in controller methods.

If Ruby allowed the default values to be introspected, web frameworks would be able to achieve a similar binding feature. For example, they could use the default to decide upon how to bind the param. They could use the default_value.class or if the default value is nil it could be specified by providing the class itself. For instance:

def an_action name: '', parent_name: String, age: Integer, date: Date.today
end

Of course, you'd need to set up the framework so that it knows how you intend parse dates and other special types from string, but this could make the developer life easier and safer against this kind of attack (like trying to instantiate a hash, etc).

An alternative would be something like:

def an_action params = {name: :string, age: :integer, date: :date}
end

You get the idea. Many APIs would be possible to be built if we're able to easily get access to the default values when inspecting a method.

Could you please consider this idea?

Actions

Also available in: Atom PDF

Like0
Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0Like0