post

Rails plugin: has_params
Rails plugin: has_params

This is yet another edition of pointless programming. Ready. Set. Go!

To me, checking if parameters exist via the params hash is ugly. My fingers start to quiver when I type params[:whatever] more than once on the same line. Sometimes I’ll add a private method to simply check if parameters exist. It just reads better, IMHO.

if using_open_id?
  # process OpenID authentication
end

private
  def using_open_id?
    !params[:openid_url].blank?
  end

Maybe you’ve done something similar, maybe you haven’t. Being the pointless programmer that I am, I wrote a plugin to take care of this for any and all parameters. I called it, has_params. You can find it on GitHub.

Example(s)

I suppose there’s no harm in duplicating the README, huh? Anyway, here’s how it works:

# the "old" way
Project.new(params[:project]) unless params[:project].blank?
Project.new(params[:project]) if params[:project]

# the "has_params" way
Project.new(params[:project]) unless blank_project_params?
Project.new(params[:project]) if has_project_params?
Project.new(params[:project]) if project_params?

You basically just plug the key that you’d otherwise use for params into the standard “has_params” format. So, for params[xxx] you’d have one of the following to choose from:

  • blank_xxx_params?
  • has_xxx_params?
  • xxx_params?

Personally, I think it cleans up controller code a little. Brick-by-brick my friends, brick-by-brick.

Gotcha!

If you’re using method_missing in your controller(s), make sure you call super at some point. This plugin also uses method_missing and at a higher point in the inheritance chain (unless you’re also mixing into ActionController::Base), so if super isn’t called, Rails will be perfectly satisfied with your version of method_missing, ignoring the has_params’ version. At least, I’m pretty sure that’s what would happen. Consider yourself warned.

Installation

I can only imagine how excited you are to install this sucker. Here’s how:

>> cd project_root/vendor/plugins
>> git clone git://github.com/rpheath/has_params.git 

And that concludes this edition of pointless programming. I hope you’ve enjoyed it :-)

Comments



Please rewrite the image text in the SPAM field: Spam Protection

Preview

2008 by Ryan Heath | Get In Touch

flickr

DesolateInfinityLooking upDazedBlurred