Class: JsRender::Renderer

Inherits:
Object
  • Object
show all
Defined in:
lib/js_render/renderer.rb

Constant Summary collapse

GLOBAL_CONTEXT =
"  var global = global || this;\n  var self = self || this;\n  var window = window || this;\n"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(component_name, data) ⇒ Renderer

Returns a new instance of Renderer.



14
15
16
17
18
19
# File 'lib/js_render/renderer.rb', line 14

def initialize(component_name, data)
  @component_name = component_name
  data = data.to_json if !data.is_a?(String)
  @json_data = data
  @uuid = SecureRandom.uuid
end

Instance Attribute Details

#component_nameObject (readonly)

Returns the value of attribute component_name.



6
7
8
# File 'lib/js_render/renderer.rb', line 6

def component_name
  @component_name
end

#json_dataObject (readonly)

Returns the value of attribute json_data.



6
7
8
# File 'lib/js_render/renderer.rb', line 6

def json_data
  @json_data
end

#uuidObject (readonly)

Returns the value of attribute uuid.



6
7
8
# File 'lib/js_render/renderer.rb', line 6

def uuid
  @uuid
end

Instance Method Details

#generate_client_scriptObject



43
44
45
46
47
48
49
50
# File 'lib/js_render/renderer.rb', line 43

def generate_client_script
  func_name = JsRender.config.client_render_function.gsub('*', @component_name)
  "    <script>\n      typeof \#{func_name} === 'function' && \#{func_name}('\#{@uuid}', \#{@json_data});\n    </script>\n  HTML\nend\n"

#generate_htmlObject



28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/js_render/renderer.rb', line 28

def generate_html
  func_name = JsRender.config.server_render_function.gsub('*', @component_name)
  server_code = "    (function () {\n      var serverStr = typeof \#{func_name} === 'function' ? \#{func_name}(\#{@json_data}) : '';\n      return '<span id=\"\#{@uuid}\">' + serverStr + '</span>';\n    })()\n  JS\n  renderer_code = js_context(find_renderer_files)\n  context = ::ExecJS.compile(GLOBAL_CONTEXT + renderer_code)\n  context.eval(server_code)\nrescue ExecJS::RuntimeError, ExecJS::ProgramError => error\n  raise Errors::ServerRenderError::new(@component_name, @json_data, error)\nend\n"

#render_componentObject



21
22
23
24
25
26
# File 'lib/js_render/renderer.rb', line 21

def render_component
  server_html = generate_html
  client_script = generate_client_script
  component = (server_html + client_script)
  component.respond_to?(:html_safe) ? component.html_safe : component
end