class Handlebars::Context

Public Class Methods

new(hbs, data) click to toggle source
# File lib/ruby-handlebars/context.rb, line 3
def initialize(hbs, data)
  @hbs = hbs
  @data = data
end

Public Instance Methods

add_item(key, value) click to toggle source
# File lib/ruby-handlebars/context.rb, line 39
def add_item(key, value)
  locals[key.to_sym] = value
end
add_items(hash) click to toggle source
# File lib/ruby-handlebars/context.rb, line 43
def add_items(hash)
  hash.map { |k, v| add_item(k, v) }
end
escaper() click to toggle source
# File lib/ruby-handlebars/context.rb, line 23
def escaper
  @hbs.escaper
end
get(path) click to toggle source
# File lib/ruby-handlebars/context.rb, line 8
def get(path)
  items = path.split('.'.freeze)
  if locals.key? items.first.to_sym
    current = locals
  else
    current = @data
  end

  until items.empty?
    current = get_attribute(current, items.shift)
  end

  current
end
get_as_helper(name) click to toggle source
# File lib/ruby-handlebars/context.rb, line 31
def get_as_helper(name)
  @hbs.get_as_helper(name)
end
get_helper(name) click to toggle source
# File lib/ruby-handlebars/context.rb, line 27
def get_helper(name)
  @hbs.get_helper(name)
end
get_partial(name) click to toggle source
# File lib/ruby-handlebars/context.rb, line 35
def get_partial(name)
  @hbs.get_partial(name)
end
with_temporary_context(args = {}) { || ... } click to toggle source
# File lib/ruby-handlebars/context.rb, line 47
def with_temporary_context(args = {})
  saved = args.keys.collect { |key| [key, get(key.to_s)] }.to_h

  add_items(args)
  block_result = yield
  locals.merge!(saved)

  block_result
end

Private Instance Methods

get_attribute(item, attribute) click to toggle source
# File lib/ruby-handlebars/context.rb, line 63
def get_attribute(item, attribute)
  sym_attr = attribute.to_sym
  str_attr = attribute.to_s

  if item.respond_to?(:[]) && item.respond_to?(:has_key?)
    if item.has_key?(sym_attr)
      return item[sym_attr]
    elsif item.has_key?(str_attr)
      return item[str_attr]
    end
  end

  if item.respond_to?(sym_attr)
    return item.send(sym_attr)
  end
end
locals() click to toggle source
# File lib/ruby-handlebars/context.rb, line 59
def locals
  @locals ||= {}
end