Sha256: 81741dbfb73b0cd1061f82bbba7268fcdbda5d1a1017126cd347e7447740274e

Contents?: true

Size: 1.17 KB

Versions: 1

Compression:

Stored size: 1.17 KB

Contents

require 'contexts/version'
require 'mapper'

module Contexts
  def self.included(base)
    base.class_eval do
      before_action :apply_contexts

      helper_method :contexts,
                    :current_context,
                    :locked_context,
                    :context_locked?
    end
  end

  def contexts
    @contexts ||= (request.env['contexts'] || {})
  end

  def current_context(key = nil)
    if key
      (ctx = contexts[key]) && ctx.current
    else
      Hash[contexts.map{ |name, ctx| [ name, ctx.current ] }]
    end
  end

  def locked_context(key = nil)
    ctx = (session[:locked_context] ||= {})

    key ? ctx[key.to_s] : ctx
  end

  def context_locked?(key = nil)
    locked_context(key).present?
  end

  def lock_context(data)
    ctx = locked_context
    ctx.merge!(data.stringify_keys).reject!{ |k, v| v.blank? }
    ctx
  end

  protected

  def apply_contexts
    contexts.each{ |name, ctx| ctx.apply(self, locked_context(ctx.key)) }
  end

  def default_url_options
    contexts.inject({}) do |options, (name, ctx)|
      option = ctx.respond_to?(:url_option) ? ctx.url_option : ctx.current
      options[ctx.key] = option
      options
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
contexts-1.0.0 lib/contexts.rb