开发者

Where to set session default value?

guys! Prior to asking i should mention, that i`m working without ActiveRecord or any self-hosted-database. So thats why i have to store some values in the session.

From the very begining i desided to set session value of the users city in the layout. - i supposed it would be loaded before anything else. So i`ve done so开发者_Go百科mething like this:

<% session[:city] ||= {:name => 'City-Name', :lat => '40', :lng => '40'}%>

But when i`m loading directly to inner page it occurs that session[:city is nil *(

How should i set the session properely, so that it wouldn`t be nil???


I had similar needs in one of the applications I worked on. It needed the users data to be loaded on sign-in and stored in the session. So, wrote a module called session_helpers.rb with the following:

module SessionHelpers
  def get_value(key)
    session[key.to_sym]
  end

  protected
    def store_data(*objects)
      objects.each do |object|
        if object.is_a?(Hash)
          object.each do |key, value|
            session[key.to_sym] = value
          end
        end
      end
    end

    def remove_data(*objects)
      objects.each do |object|
        if object.is_a?(String)
          key = to_id(object)
        else
          key = to_id(object.class.name)
        end
        session[key] = nil
      end
    end

    def update_data(key, value)
      session[key.to_sym] = value
    end

  private
    def to_id(name)
      "#{name.parameterize('_').foreign_key}".to_sym
    end
end

You can make any or all the methods available to views as well:

# application_controller.rb
helper_method :get_value

From the model I would retrieve a hash of the data that needs to be put up in the session about the user:

def common_data
  @data = Hash.new

  @data.merge!( { 'news'         => self.news.count } )
  ...
  @data
end

As I wanted to do this after sign-in I overrode the devise method to do this:

def after_sign_in_path_for(resource_or_scope)
  store_data( '_count', current_user.common_data )

  dashboard_path
end

This way I was able to load important data about the user on sign-in and store it in the session and retrieve whenever I wanted. Hope this helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜