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, #volt_app

Instance Method Summary collapse

Methods inherited from BaseBinding

#browser, #dom_section, #getter_fail, #remove_anchors

Constructor Details

#initialize(volt_app, 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
24
25
# File 'lib/volt/page/bindings/content_binding.rb', line 9

def initialize(volt_app, target, context, binding_name, getter)
  super(volt_app, target, context, binding_name)
  @getter = getter

  # Listen for changes
  @computation = lambda do
    begin
      @context.instance_eval(&getter)
    rescue => e
      getter_fail(e)
      ''
    end
  end.watch_and_resolve!(
    method(:update),
    method(:getter_fail)
  )
end

Instance Method Details

#html_escape(str) ⇒ Object



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

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

#removeObject



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

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

  super
end

#update(value) ⇒ Object



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

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