Rob Okin
Rob Okin

Reputation: 173

How to use reusable controller methods in Rails?

I'm relatively new to Rails and am working on creating a simple user authentication system to get to grips with how Rails works.

I'm currently at the point where I'd like to create some methods that I can use in my controllers like so:

is_logged? # => true

and

current_user_id # => 6

These would be used to interact with sessions, mainly so I'm not repeating myself in the controller.

Where would I define these functions and how would I include them in a controller?

Thanks a lot in advance for any help.

Upvotes: 3

Views: 1036

Answers (1)

Kumar
Kumar

Reputation: 3126

Method 1

You can define these method in helper files, inside app/helpers/my_module.rb. You can create a module there, put all the methods inside of it, and then include the modules in your control to use these method.

module MyMoule
  def is_logged?
    ...
  end
end

Then in you class include the module

class MyClassController < ApplicationController
  include MyModule

  def my_method
    #Use it like this
    logged_in = MyModule.is_logged?
  end
end

Method 2

If you using session related stuff you can always put them inside application_controller.rb. And since all your controller will inherit ApplicationController the methods will be available to you.

class ApplicationController < ActionController::Base
  def is_logged?
    ...
  end
end

In your other controller you can use them directly.

class MyClassController < ApplicationController
  def my_method
    logged_in = is_logged?
  end
end

Upvotes: 7

Related Questions