Class: Snp::TemplateContext

Inherits:
Object
  • Object
show all
Defined in:
lib/snp/template_context.rb

Overview

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')

Defined Under Namespace

Classes: InsufficientContext

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(context) ⇒ TemplateContext

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.



36
37
38
39
40
41
42
43
# 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

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method) ⇒ Object

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.



57
58
59
# File 'lib/snp/template_context.rb', line 57

def method_missing(method, *)
  raise InsufficientContext.new(method)
end

Class Method Details

.for(attributes) ⇒ Object

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



26
27
28
# File 'lib/snp/template_context.rb', line 26

def self.for(attributes)
  new(attributes).erb_binding
end

Instance Method Details

#erb_bindingObject



45
46
47
# File 'lib/snp/template_context.rb', line 45

def erb_binding
  binding
end

#respond_to_missing?(method) ⇒ Boolean

Returns:

  • (Boolean)


49
50
51
# File 'lib/snp/template_context.rb', line 49

def respond_to_missing?(method, *)
  @context.has_key?(normalize(method))
end