views:

14

answers:

1

I need to define some common piece of code that can be invoked from different controllers(not view). Is there a way to do that in Rails v3?

I have defined the code in ApplicationHelper and tried to invoke it using

@template.<helper_method>

and

ActionController::Base.helpers.<helper_method>

But it does not work?

A: 

Code that you will invoke in controllers can be defined as protected methods in their parent, ApplicationController.

app/controllers/application_controller.rb:

class ApplicationController

  # ...

  protected

  def work_some_magic(param)
    # work magic here
  end
end

app/controllers/users_controller.rb:

class UsersController < ApplicationController

  # ...

  def show
    @user = User.find(params[:id])
    @magic_result = work_some_magic(@user)
  end
end
Matchu
thanks of course, how did i miss that :) also what if I want to call this common code from my code sitting inside the "lib" dir
@user310525: If you need it in models and the like, too, `lib` is a good choice. Create a module named `MagicWand` or whatever in `lib/magic_wand.rb`, then put `require 'magic_wand'` at the top of each file where you need it.
Matchu