Global method in Rails

If you are familiar with Devise, you might know very well what is current_user. Imagine now you have a several controllers which relate to another object model, example: Project instead of User, and you want to define current_project for your actions in different controllers? I think of a solution, that is to store current_project in cookies, we can get or set this value.

  • First, we should create a projects_controller:
class ProjectsController < ApplicationController
  def current_project
    return cookies[:current_project] ? cookies[:current_project] : Project.first 
  end

  # Set this method as helper method to be able to use in views
  helper_method :current_project
end
  • Then, in other controllers you can inherit that ProjectsController:
class Manager::ProjectsController < ProjectsController
end

class Developer::ProjectsController < ProjectsController
end
  • Or views:
<%= current_project %>
  • You can create an action to change it if necessary
def change_current_project
  cookies.permanent[:current_project] = params[:current_project]
  redirect_to request.referer || root_url
end

Have fun programming!

Published by

Colin Dao

I am a hardworking Rubyist in Hanoi, Vietnam

Leave a comment