Tuesday, November 30, 2010

[Rails] Re: Checking parameters

On Nov 29, 3:30 pm, turkan <kai.schl...@googlemail.com> wrote:
> Hi.
>
> I am often checking the same parameters (like param[:page] and
> param[:per_page]) in models over and over again (are those in a
> specific range ... if not use defaults):
> page = !options[:page].blank? && options[:page] =~ /^[0-9]+$/ &&
> options[:page].to_i > 0 ? options[:page].to_i : 1
> per_page = !options[:per_page].blank? && options[:per_page] =~ /^[0-9]+
> $/ && options[:per_page].to_i > 0 && options[:per_page].to_i <= 100 ?
> options[:per_page].to_i : 10
>
> How can I make this more DRY and easier to read?

For a start, make use of the fact that Ruby is not Java. For instance:

''.to_i # => 0
nil.to_i # => 0
'blargh'.to_i # => 0
'123foo'.to_i # => 123

That last one is arguably weird, but reasonable.

Secondly, for range-ish cases you might want to use some of the Array
functions. Your first case becomes:

[1, options[:page].to_i].max

the second (this is not as clear):

[100, [1, options[:per_page].to_i].max].min

or, if you don't mind scribbling on the options hash:

options[:per_page] = 10 unless (1..100).include?
(options[:per_page].to_i)

--Matt Jones

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home


Real Estate