JasonDaly.name

PHP, Ruby, Symfony, Rails, Doctrine, MooTools. Web Development.
May 19, 2011

Using intern to Reference Routes Dynamically

In config/routes.rb if routes such as the following exist:

match "users/customers" => "users#customers", :as => :users_customers, :via => :get
match "users/employees" => "users#employees", :as => :users_employees, :via => :get 

match "users/:id/toggle-status" => "users#toggle_status", :as => :users_toggle_status, :via => :put

the views associated with the :users_customers and :users_employees actions above (in this case each displaying a list-view of users of the specified type) likely both have a link referencing the :users_toggle_status route.

Within the toggle_status action the route to redirect back to can be determined by looking at the type of user who’s status is being toggled. A sample version of this action is below.

def toggle_status
    user = User.find(params[:id])
    user.toggle_status!

    if user.type == 'employee'
      redirect_to :users_employees and return
    end

    redirect_to :users_customers and return
end

The condition above and multiple redirect_to’s is cumbersome and unnecessary. Instead, we can use Ruby’s intern method for strings.

def toggle_status
    user = User.find(params[:id])
    user.toggle_status!

    redirect_to ('users_%s' % user.type).intern and return
end

11 notes Tags: ruby rails ruby on rails RoR intern string tips code

  1. d4ly posted this