Hi! Thanks for visiting my blog. If you've received any value from my content would you mind supporting my new startup by downloading our browser add-on? It's called PriceBlink and makes online shopping a breeze. You can watch it in action here and download it for Chrome, Firefox, IE, or Safari by going to PriceBlink.com. Thank you and I hope you enjoy!

Ruby on Rails Conditional Assigment Operator

Apr 16

I’ve found an interesting operator that I’d like to share.  I’m pretty fascinated with it because in ColdFusion I fell in love with cfparam for assigning default values that could be overridden.  You can achieve the same in Ruby on Rails using the conditional assigment operator.  This comes in handy when setting session or even url variables.  An example of its usage looks like:

def yourmethod
@params[:name] ||= ‘dennis baldwin’
end

That’s how it would be defined in your controller and displaying it within your view would look like:

Hello <%= @params[:name] %>

By default this would display Hello dennis baldwin. Now passing a url parameter called name into your controller would yield different results.  Let’s say that it looks something like http://www.yourapp.com/yourcontroller/yourmethod?name=somebody, then you would see Hello somebody.  The default value is overridden and the specified value is displayed.  Once again Rails makes this extremely clean and simple.

Leave a Reply