class Snp::TemplateContext

Snp::TemplateContext

This class aims to represent the context in which a snippet template is compiled. It receives a hash of keys and values that act as properties to be used in the template. For example, if you have a template with the content:

<html>
  <head><title><%= title %></title></head>
</html>

Then a proper context for this snippet compilation would be:

TemplateContext.for(title: 'My beautiful page')

Public Class Methods

for(attributes) click to toggle source

Public: returns the binding for the passed `attributes`.

# File lib/snp/template_context.rb, line 26
def self.for(attributes)
  new(attributes).erb_binding
end
new(context) click to toggle source

Public: creates a new Snp::TemplateContext object.

context - a hash of properties and values to be used in as context of the template.

The hash is used so that the resulting object responds to each key in `context`, returning the accoring value.

# File lib/snp/template_context.rb, line 36
def initialize(context)
  @context = context

  context.each do |property, value|
    method_name = normalize(property)
    define_property(method_name, value)
  end
end

Public Instance Methods

erb_binding() click to toggle source
# File lib/snp/template_context.rb, line 45
def erb_binding
  binding
end
method_missing(method, *) click to toggle source

In case an unknown method is called on the template context, we raise a proper exception that must be rescued and properly handled.

Reaching this point means we need variables in the snippet that were not provided.

# File lib/snp/template_context.rb, line 57
def method_missing(method, *)
  raise InsufficientContext.new(method)
end
respond_to_missing?(method, *) click to toggle source
# File lib/snp/template_context.rb, line 49
def respond_to_missing?(method, *)
  @context.has_key?(normalize(method))
end

Private Instance Methods

define_property(property, value) click to toggle source

Internal: defines a method with `property` name, and returning `value`. If `value` is a boolean, this method will also define a predicate method.

# File lib/snp/template_context.rb, line 77
def define_property(property, value)
  define_singleton_method(property) { value }

  if value == true || value == false
    define_singleton_method("#{property}?") { value }
  end
end
normalize(name) click to toggle source

Internal: returns a propperty name with underscores where dashes were present.

name - the property name.

Examples

prepare('name')       # => 'name'
prepare('update-ref') # => 'update_ref'
# File lib/snp/template_context.rb, line 71
def normalize(name)
  name.to_s.gsub('-', '_')
end