Sha256: 2a189f78fae6e4c73fb72e9f942841fbdd3d44e6d9fe9c975ae6cd1b6a224a5d

Contents?: true

Size: 1.56 KB

Versions: 5

Compression:

Stored size: 1.56 KB

Contents

module Nanoc::Int
  # Provides a context and a binding for use in filters such as the ERB and
  # Haml ones.
  #
  # @api private
  class Context
    # Creates a new context based off the contents of the hash.
    #
    # Each pair in the hash will be converted to an instance variable and an
    # instance method. For example, passing the hash `{ :foo => 'bar' }` will
    # cause `@foo` to have the value `"bar"`, and the instance method `#foo`
    # to return the same value `"bar"`.
    #
    # @param [Hash] hash A list of key-value pairs to make available
    #
    # @example Defining a context and accessing values
    #
    #     context = Nanoc::Int::Context.new(
    #       :name     => 'Max Payne',
    #       :location => 'in a cheap motel'
    #     )
    #     context.instance_eval do
    #       "I am #{name} and I am hiding #{@location}."
    #     end
    #     # => "I am Max Payne and I am hiding in a cheap motel."
    def initialize(hash)
      hash.each_pair do |key, value|
        # Build instance variable
        instance_variable_set('@' + key.to_s, value)

        # Define method
        metaclass = (class << self; self; end)
        metaclass.send(:define_method, key) { value }
      end
    end

    # Returns a binding for this instance.
    #
    # @return [Binding] A binding for this instance
    # rubocop:disable Style/AccessorMethodName
    def get_binding
      binding
    end
    # rubocop:enable Style/AccessorMethodName

    def include(mod)
      metaclass = class << self; self; end
      metaclass.instance_eval { include(mod) }
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
nanoc-4.4.4 lib/nanoc/base/entities/context.rb
nanoc-4.4.3 lib/nanoc/base/entities/context.rb
nanoc-4.4.2 lib/nanoc/base/entities/context.rb
nanoc-4.4.1 lib/nanoc/base/entities/context.rb
nanoc-4.4.0 lib/nanoc/base/entities/context.rb