Sha256: b232affdd5a568ec959c49ab4219779a81cc11254b1b065e0bc886e5bf19b4e5

Contents?: true

Size: 1.11 KB

Versions: 2

Compression:

Stored size: 1.11 KB

Contents

require 'contexts/version'
require 'contexts/base'
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
    options = super
    contexts.each{ |name, ctx| options[ctx.key] = ctx.url_option }
    options
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
contexts-0.1.1 lib/contexts.rb
contexts-0.1.0 lib/contexts.rb