Sha256: 41e2ee8352d19348ef26dd55ce08e259f3fe63361833b442ce9468608de20655

Contents?: true

Size: 1.5 KB

Versions: 9

Compression:

Stored size: 1.5 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)
      metaclass = class << self; self; end
      hash.each_pair do |key, value|
        instance_variable_set('@' + key.to_s, value)
        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

9 entries across 9 versions & 1 rubygems

Version Path
nanoc-4.6.0 lib/nanoc/base/entities/context.rb
nanoc-4.5.4 lib/nanoc/base/entities/context.rb
nanoc-4.5.3 lib/nanoc/base/entities/context.rb
nanoc-4.5.2 lib/nanoc/base/entities/context.rb
nanoc-4.5.1 lib/nanoc/base/entities/context.rb
nanoc-4.5.0 lib/nanoc/base/entities/context.rb
nanoc-4.4.7 lib/nanoc/base/entities/context.rb
nanoc-4.4.6 lib/nanoc/base/entities/context.rb
nanoc-4.4.5 lib/nanoc/base/entities/context.rb