Caution! - Many of these posts are creepy-old in the Ruby on Rails world (before 1.0!)
The :author => Charles Abbott now blogs here

verify ... 5.times do cycle

2006-09-25   [ 0 comments ]

Today I am going to cover a very useful ActionController method that is straight from ActionController::Verification module - and is documented in the rails api. Verify will help you manage access to your controller's methods based on several different criteria - and I plan on covering the most useful (in my opinion!). Second I am going to cover a simple but useful ActionView helper - cycle.

So, lets get to the really cool ActionController method - verify. Verify is much like a before_filter - except it allows you to filter access to certain actions with a much finer control and by multiple criteria.

My first reaction to seeing verify in the API was total joy - I had a need to prevent access to an action in one of my controllers unless it were solely an AJAX request (just for added security) - and verify quickly provided the functionality I needed. So how do you use verify in your controller?

Just like before_filter - you place verify outside of your actions, within the controller class definition. Then you pass it your options in an easy to read :symbol => "value", :symbol => "value" setup. So - here is an example out of one of my controllers:

class UserController < ApplicationController

verify :params => "c", :xhr => TRUE, :only => "ajaxdump", :redirect_to => {:action => "index"}

def index
       ... index stuff here
end

def ajaxdump
       ...ajax calls here
end
end

In this example - verify gets 2 requirements for the ajaxdump action before a visitor is allowed to access it. First - there must be a key in the param array that matches "c", and second (and what made me so happy) is that the :xhr => TRUE requires that the request must be an AJAX request. If both of these assertions are not met then the user's browser is kindly redirected to the index action. So simple, yet so effective!

There are several options you can use, in fact - for easy reference, let me list the options and descriptions that are in the API:

* :params -- a single key or an array of keys that must be in the params hash in order for the action(s) to be safely called.

* :session -- a single key or an array of keys that must be in the @session in order for the action(s) to be safely called.

* :flash -- a single key or an array of keys that must be in the flash in order for the action(s) to be safely called.

* :method --a single key or an array of keys—any one of which must match the current request method in order for the action(s) to be safely called. (The key should be a symbol: :get or :post, for example.)

* :xhr --true/false option to ensure that the request is coming from an Ajax call or not.

* :add_flash -- a hash of name/value pairs that should be merged into the session’s flash if the prerequisites cannot be satisfied.

* :redirect_to --the redirection parameters to be used when redirecting if the prerequisites cannot be satisfied.

* :render -- the render parameters to be used when the prerequisites cannot be satisfied.

* :only --only apply this verification to the actions specified in the associated array (may also be a single value).

* :except --do not apply this verification to the actions specified in the associated array (may also be a single value).

As you can see - this is a very useful method that you can quickly slap into your controller to further control access to certain methods. If you need to make certain that 2 params are set, and that the method was indeed a post (no modified urls!) simply write something like this:

verify :params => {"username", "password"}, :method => :post, :only => "authenticate", :redirect_to => {:action => "login" }

That would work great for an authentication system - if the params are not set, redirect before you even do anything else - and as one of the options above suggests - you can even insert something into the :flash to explain the problem to your visitor. Very cool...

Well, now on to the other part of this post, the one that will take all of 3 paragraphs to explain. The useful, and probably overlooked, ActionView method - cycle. Cycle allows you to easily swap between options when working inside your views. Consider the following:

<% 5.times do %>
<div class=<%= cycle("blue","red","green")%>">Changing Classes!</div>
<% end %>

This simple loop prints out a div each time through, and like many tables with rows - you may want each div to stand out from each other. And what better way than to have the divs cycle through different classes - in which you can define the CSS to change background colors or font styles.

Cycle is called once in each iteration of the loop - and it simply pulls the next item in the group of options. So first time through it prints 'blue' second time 'red' and third 'green' - on the fourth run through it returns to 'blue' as you would expect.

But what if you needed to reset the internal cycle for some reason?

easy -- use the ready made answer reset_cycle(). To do this you will have to make one minor change to your cycle declaration:

cycle("red", "blue", "green" :name => "mycycle")

... and your reset_cycle() would be:

reset_cycle("mycycle")

Well thats it - verify is a pretty cool method - and I can definitely see value in its existence. Cycle is also pretty nifty - it can help save a bit of time and is so simple to remember. Of course, if you ever forget you can find them both in the Rails API. Until next post - happy coding!

:author => "Charles Abbott"
Rails Methods make my life simpler
 

What?

Who?              Link?



Frameworks Good or Bad?   :date => "2007-10-06"
Where is ForTheCode.com Going?   :date => "2007-09-23"
Refactoring - Vital to Software Development   :date => "2007-09-23"
Mongrel Cluster a quick note - and extra notes   :date => "2007-05-20"
Linux Mongrel and Rails   :date => "2007-05-15"
form_remote_tag revisited   :date => "2007-01-07"
How To: Ubuntu 6.10 Edgy on Rails part 3   :date => "2006-12-30"
How To: Ubuntu 6.10 Edgy on Rails part 2   :date => "2006-12-24"
How To: Ubuntu 6.10 Edgy on Rails   :date => "2006-12-22"
verify ... 5.times do cycle   :date => "2006-09-25"
country_select, country_options_for_select, mail_to   :date => "2006-09-05"
Generate and Send Email in Rails   :date => "2006-08-26"
FDF Model, gsub, and send_data   :date => "2006-08-18"
Active Directory Authentication with acts_as_authenticated   :date => "2006-08-17"
Apache2 proxy with Lighttpd - FastCGI for Rails   :date => "2006-08-08"
reverse! && a simple file Upload Class   :date => "2006-07-29"
send_file - a link to download a file   :date => "2006-07-24"
Environments (production, development, test) and cache_pages   :date => "2006-07-04"
.class .methods .instance_variables   :date => "2006-06-14"
select_tag :multiple => true   :date => "2006-06-01"
FileUtils, action_controller rescues   :date => "2006-05-20"
file_field_tag, File.size, File.path, FileUtils.mv   :date => "2006-05-15"
javascript_include_tag, stylesheet_link_tag   :date => "2006-05-02"
submit_to_remote, form_remote_tag, script.aculo.us   :date => "2006-04-30"
periodically_call_remote, simple_format   :date => "2006-04-26"
observe_field - Ajax!   :date => "2006-04-21"
h method, TextHelper, sanitize(), strip_tags()   :date => "2006-04-15"
Rails API :My API [.count(), link_to, text_area :size]   :date => "2006-04-13"
Rails - HTML Select Tag   :date => "2006-04-05"
Pruning Old Sessions   :date => "2006-03-21"
If Elsif Else, and Searching Too!   :date => "2006-03-17"
SHA1 - A quick update   :date => "2006-03-15"
Initialized! good, Authorized? Great! part 2   :date => "2006-03-11"
Initialized! good, Authorized? Great!   :date => "2006-03-08"
Forms and Routing in RoR   :date => "2006-03-06"
My First RoR Post !   :date => "2006-03-05"