lifecoder
lifecoder

Reputation: 1434

How to create and use global static class/singleton in rails?

I need some class or singleton object globally-accessible in controllers and easy to use. Now it is implemented in the libs/ folder like this:

class User
  class << self

    @user = nil
    attr_reader :uid, :name

    def init session
      if session[:user_info].nil?
        @user = nil
      end

      @user = session_data[:user]
    end

    def signed_in?
      @user.nil? ? false : true
    end

    def guest?
      not signed_in?
    end

  end
end

This code obviously is not good, as User initialized only once on application start, and in case of improper use User wouldn't be updated. I want to save ability to use the class or object without much addition steps, but have a new global instance for every new connection. How it should be done?

Upvotes: 0

Views: 1578

Answers (3)

Jimmy
Jimmy

Reputation: 37131

It looks like you're trying to create a standard "current user" method. I think you're complicating things a bit. All you need to do is load a user object based on session information and cache it in an instance variable. Something like this:

class ApplicationController < ActionController::Base
  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end
end

The first time you call it, it will look up the current user based on the ID stored in the session. Subsequent calls will return the user object you already loaded. If the user is not signed in, current_user will simply be nil.

Upvotes: 1

sjain
sjain

Reputation: 23356

Place the code in Application Controller as this is the base class of all the classes. Doing so it will be globally-accessible in all the controllers as well.

Upvotes: 0

Hck
Hck

Reputation: 9167

You can add include Singleton to your User class definition and then use User.instance go get the user instance.

Upvotes: 1

Related Questions