Want to stay on top? Ruby Weekly is a once-weekly e-mail newsletter covering the latest Ruby and Rails news.
     Feed Icon

Pre-processing / normalizing parameters in Rails

By Peter Cooper / July 15, 2006

Bruce Williams tries to solve the problem of multiple parameter types in Rails. For example, an action may accept dates via a parameter, but dates may be supplied in many forms. A 'date' parameter might arrived as if from a date_select helper, or might even be typed in directly by a user, or be pulled from a database. Rather than use before_filters to check parameters and normalize them, Bruce suggests that it should be possible to add basic conversion tools to certain data types so that all data is normalized by the time it hits your controllers.

Bruce provides a simple example to demonstrate how two different types of date could be prenormalized:

ActionController::Base.add_param_type 'date' do |value|
  case value
  when String
    Date.parse(value)
  when Hash
    Date.new(Integer(value['year']), Integer(value['month']), Integer(value['day']))
  end
end

His ideas are available in a plugin called param_types. Learn more about how to install and use it in his blog post.

Comments

  1. Gareth says:

    I stopped reading the article as soon as he mentioned "AJAX calendar". Just because you're using Rails doesn't leave you free to use as many irrelevant buzzwords as you like. I really doubt that date selecct widget does use XmlHTTPRequest, and if it does then it's ridiculously overengineered

  2. Bruce says:

    Gareth, the use of "AJAX" (even with "Calendar") hardly constitutes irrelevancy (or even full buzzword compliance, I think), and if you'd read a little further you'd notice the plugin has nothing whatsoever to do with AJAX-- or XmlHTTPRequest, if you prefer to be formal and pedantic.

    And no, date select (and friends), are engineered *just right,* you'll be happy to know. Of course, the API documentation makes that pretty clear (watch out, though, they use that scary "AJAX" word in there, too).

  3. Peter Cooper says:

    I'm sorry you seem to be getting a bit of flak in both the posts here, Bruce. I think your work is great (which is why I link to it :)).

  4. Bruce says:

    Thanks, Peter.

    It's no big deal, though; in this community we [generally] run across constructive criticism-- and that's something I enjoy receiving.

Other Posts to Enjoy

Twitter Mentions