Sha256: c10d1481319e5e5374c8fe6f2205913e1fda8a41a3931d5067462eee712ca11f

Contents?: true

Size: 1.96 KB

Versions: 1

Compression:

Stored size: 1.96 KB

Contents

module StickyParams
  class StrongSessionParams
    attr_reader :controller
    attr_accessor :prefix

    def initialize(controller)
      @controller = controller
      @prefix = "#{controller.controller_name}_#{controller.action_name}_"
    end

    def fetch_from_params(name, session_param_name)
      if controller.params[name].present?
        if controller.params[name].is_a?(ActionController::Parameters)
          controller.session['sticky_params'][session_param_name] = controller.params[name].to_unsafe_hash
        else
          controller.session['sticky_params'][session_param_name] = controller.params[name]
        end
        controller.params[name]
      else
        controller.session['sticky_params'].delete session_param_name
        nil
      end
    end

    def fetch_from_session(session_param_name)
      result = controller.session['sticky_params'][session_param_name]
      # covert hash to action parameters for simulating a normal param
      result.is_a?(Hash) ? ActionController::Parameters.new(result) : result
    end

    def [](name)
      session_param_name = "#{prefix}#{name}"
      controller.session['sticky_params'] ||= {}
      if controller.params[name]
        fetch_from_params(name, session_param_name)
      elsif controller.session['sticky_params'][session_param_name]
        fetch_from_session(session_param_name)
      end
    end

    def []=(name, value)
      session_param_name = "#{prefix}#{name}"
      controller.session['sticky_params'] ||= {}
      controller.session['sticky_params'][session_param_name] = controller.params[name] = value
    end

    # clears all sticky params for the current controller/action name
    def clear!
      if controller.session['sticky_params'].present?
        controller.session['sticky_params'].reject! do |key, _value|
          key.index(prefix) == 0
        end
      end
    end

    # clears all sticky parameters
    def clear_all!
      controller.session.delete('sticky_params')
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
sticky_params-2.1.0 lib/sticky_params/strong_session_params.rb