Sha256: 04b126560e0d9f3de571f1d66d2d3e53eab0495107aaaa6dcdd36d1a18ac3fe3

Contents?: true

Size: 1.25 KB

Versions: 8

Compression:

Stored size: 1.25 KB

Contents

require 'active_support/concern'

module Neo
  module Rails
    # A really simple version of exposing variables to the view.
    # Bases on attr_reader and helper_method.
    module Exposure
      extend ActiveSupport::Concern

      class UndeclaredVariableError < StandardError; end

      included do
        class_attribute :exposed_vars
        self.exposed_vars ||= Set.new
      end

      module ClassMethods
        # Defines the variables to be exposed.
        def exposes(*names)
          exposures = names.map(&:to_sym)
          self.exposed_vars.merge exposures
          attr_reader *exposures
          helper_method *exposures
        end
      end

      # Expose an assign at the instance level.
      #
      # If the value is given with a block, just execute the block
      # if a value was not set yet.
      #
      # Raise UndeclaredVariableError if access variable wasn't declared before.
      def expose(key, value=nil)
        name = key.to_sym
        raise UndeclaredVariableError unless self.class.exposed_vars.include?(name)

        value = yield if block_given?

        self.instance_variable_set("@#{name}", value)
      end

      private

      def exposed?(name)
        instance_variable_get("@#{name}")
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
neo-rails-0.1.0 lib/neo/rails/exposure.rb
neo-rails-0.0.8 lib/neo/rails/exposure.rb
neo-rails-0.0.7 lib/neo/rails/exposure.rb
neo-rails-0.0.6 lib/neo/rails/exposure.rb
neo-rails-0.0.5 lib/neo/rails/exposure.rb
neo-rails-0.0.4 lib/neo/rails/exposure.rb
neo-rails-0.0.3 lib/neo/rails/exposure.rb
neo-rails-0.0.2 lib/neo/rails/exposure.rb