Sha256: ff5ec6d08386c8fe9b62cfc5fcbd2f8282e57f1f0f296b99c0dcb768e7c99c21

Contents?: true

Size: 1.49 KB

Versions: 2

Compression:

Stored size: 1.49 KB

Contents

require 'active_support/concern'
require 'neo/rails/exposure/exposures'

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

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

      def exposures
        @exposures ||= Exposures.new(self.class.exposure_names)
      end

      module ClassMethods
        # Defines the variables to be exposed.
        def exposes(*names)
          exposure_names = names.map(&:to_sym)
          self.exposure_names.merge exposure_names

          # Define a helper method for each exposure
          # see Rails: /actionpack/lib/abstract_controller/helpers.rb
          helper do
            exposure_names.each do |exposure_name|
              define_method exposure_name do
                controller.exposures[exposure_name]
              end
            end
          end
        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
        value = yield if block_given?
        self.exposures[key] = value
      end

      private

      def exposed?(key)
        self.exposures.exposed?(key)
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
neo-rails-0.2.2 lib/neo/rails/exposure.rb
neo-rails-0.2.1 lib/neo/rails/exposure.rb