donald
donald

Reputation: 23737

Rails 3: Call functions inside controllers

If I want to have functions to be called inside controllers, where should I put them?

Upvotes: 11

Views: 12232

Answers (4)

ddayan
ddayan

Reputation: 4142

if you want it to be local to a controller then all you need to do is to add it to the controller you wish to use.

private
def myfunction
  function code.....
end

to all controllers you can put it inside the application controller, because all controlers are sub classed.

ApplicationController

protected

def myfunction

  function code.....

end

If you want access in your views then you can create a helper

ApplicationHelper

def myfunction

  function code...

end

Upvotes: 14

kikito
kikito

Reputation: 52648

@jonnii, for example, I want to call a function that returns a generated unique code.

If your generated code is going to be used only on your controllers, put the function inside a controller, as protected function (the easiest way would be putting it inside ApplicationController).

If you need to call the function on the views, then put it on a helper, like ddayan says.

If you also need to invoke the function from models, then the simplest way to do it is by putting a module inside the /lib/ directory.

# /lib/my_module.rb
module MyModule
  def generate_code
    1
  end
end

You will also need to include it with an initializer:

#/config/initializers/my_module.rb
require 'my_module'

From that moment on, you can use the function like this:

MyModule::generate_code

If you are doing this very often, consider creating a gem.

Upvotes: 4

standup75
standup75

Reputation: 4814

The ApplicationController is here for that, since every Controller inherited from it.

Upvotes: 0

megas
megas

Reputation: 21791

class YourController < ActionController::Base

  def your_action
    your_function
  end

  private

    def your_function

    end
end

Also look at before_filter and after_filter, they're often useful in such kind of things

Upvotes: 3

Related Questions