I often find myself running code like this:
my_instance = MySequelModel[params[:id].to_i]
Being used to develop in Grails as well (my application is partly
written in Grails, part in Rails and part with some other technologies),
we have the option of automatic params binding there by using the
support for optional typing parameters provided by the Groovy language:
def an_action(Long id, String name) {
// id and name have been automatically bound here to the declared
types Long and String
}
While the Ruby language does not allow for optional typing yet, I tried
to propose that the Method#parameters would get the default value as the
last item in the array for each param, but I couldn''t persuade Matz:
https://bugs.ruby-lang.org/issues/8629
So, I''d like to propose another kind of solution for Rails controllers
to both increase security when handling params as well as making it
simpler to deal with them in the code:
def an_action
params = params.bind required: {id: Integer, name: String},
optional: {page: 1}
(render text: ''invalid request''; return) unless
params.valid? #
either id or name haven''t been informed
params.page # 1 if page param is not present or 2 if page param is
''2''. The binding class is default.class unless Class ===
default
end
Alternatively we could get params.bind! to raise if it''s invalid.
Also, if the hash doesn''t include a :required or :optional key mapping
to a hash, it should assume the hash should be interpreted as optional:
original_hash.
I''m not sure how to deal with dates and other more complex binding
rules, but I''m sure we can deal with them in many customizable ways.
I''m
just leaving the details out here because I''m mostly concerned about
getting the main idea approved or open for discussion.
Also, I assigned the result of params.bind to a local variable called
''params'' but it could be named anything else in case you want
to access
the original params method without using self.params. Also, if you want
to access the raw value of any param, automatically bound or not, you
could use params[:any_param_name] as usual, assuming params is the local
variable here resulted from the original params.bind call.
Additional, we could add some methods to the original params object
specific for data binding like params.int(), params.date(),
params.time(), params.string(), params,int_array() and so on.
Any chances something like this could get into ActionPack?
--
You received this message because you are subscribed to the Google Groups
"Ruby on Rails: Core" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to rubyonrails-core+unsubscribe@googlegroups.com.
To post to this group, send email to rubyonrails-core@googlegroups.com.
Visit this group at http://groups.google.com/group/rubyonrails-core.
For more options, visit https://groups.google.com/groups/opt_out.