Class: Volt::ContentBinding

Inherits:
BaseBinding show all
Defined in:
lib/volt/page/bindings/content_binding.rb

Constant Summary collapse

HTML_ESCAPE_REGEXP =
/[&"'><\n]/
HTML_ESCAPE =
{ '&' => '&amp;',  '>' => '&gt;',   '<' => '&lt;', '"' => '&quot;', "'" => '&#39;', "\n" => "<br />\n" }

Instance Attribute Summary

Attributes inherited from BaseBinding

#binding_name, #context, #target

Instance Method Summary collapse

Methods inherited from BaseBinding

#dom_section, #remove_anchors

Constructor Details

#initialize(page, target, context, binding_name, getter) ⇒ ContentBinding

Returns a new instance of ContentBinding.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/volt/page/bindings/content_binding.rb', line 9

def initialize(page, target, context, binding_name, getter)
  super(page, target, context, binding_name)

  # Listen for changes
  @computation = -> do
    begin
      res = @context.instance_eval(&getter)
    rescue => e
      Volt.logger.error("ContentBinding Error: #{e.inspect}")
      ''
    end
  end.watch_and_resolve! do |result|
    update(result)
  end
end

Instance Method Details

#html_escape(str) ⇒ Object



47
48
49
50
51
52
# File 'lib/volt/page/bindings/content_binding.rb', line 47

def html_escape(str)
  # https://github.com/opal/opal/issues/798
  str.gsub(HTML_ESCAPE_REGEXP) do |char|
    HTML_ESCAPE[char]
  end
end

#removeObject



54
55
56
57
58
59
60
61
# File 'lib/volt/page/bindings/content_binding.rb', line 54

def remove
  if @computation
    @computation.stop
    @computation = nil
  end

  super
end

#update(value) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/volt/page/bindings/content_binding.rb', line 25

def update(value)
  value = (value || '').to_s unless value.is_a?(String)
  html_safe = value.html_safe?

  # Exception values display the exception as a string
  value = value.to_s

  # Update the html in this section
  # TODO: Move the formatter into another class.

  # The html safe check lets us know that if string can be rendered
  # directly as html
  unless html_safe
    # Escape any < and >, but convert newlines to br's, and fix quotes and
    value = html_escape(value)
  end

  # Assign the content
  dom_section.html = value
  # dom_section.text = value
end