Class: JsRender::Renderer
- Inherits:
-
Object
- Object
- JsRender::Renderer
- Defined in:
- lib/js_render/renderer.rb
Constant Summary collapse
- GLOBAL_CONTEXT =
<<-JS var global = global || this; var self = self || this; var window = window || this; JS
Instance Attribute Summary collapse
-
#component_name ⇒ Object
readonly
Returns the value of attribute component_name.
-
#json_data ⇒ Object
readonly
Returns the value of attribute json_data.
-
#uuid ⇒ Object
readonly
Returns the value of attribute uuid.
Instance Method Summary collapse
- #generate_client_script ⇒ Object
- #generate_html ⇒ Object
-
#initialize(component_name, data) ⇒ Renderer
constructor
A new instance of Renderer.
- #render_component ⇒ Object
Constructor Details
#initialize(component_name, data) ⇒ Renderer
Returns a new instance of Renderer.
14 15 16 17 18 19 20 21 22 |
# File 'lib/js_render/renderer.rb', line 14 def initialize(component_name, data) @component_name = component_name unless data.is_a?(String) transform_keys(data) data = data.to_json end @json_data = data @uuid = SecureRandom.uuid end |
Instance Attribute Details
#component_name ⇒ Object (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_data ⇒ Object (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 |
#uuid ⇒ Object (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_script ⇒ Object
48 49 50 51 52 53 54 55 |
# File 'lib/js_render/renderer.rb', line 48 def generate_client_script func_name = JsRender.config.client_render_function.gsub('*', @component_name) <<-HTML <script> typeof #{func_name} === 'function' && #{func_name}('#{@uuid}', #{@json_data}); </script> HTML end |
#generate_html ⇒ Object
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/js_render/renderer.rb', line 31 def generate_html return "<span id=\"#{@uuid}\"></span>" unless JsRender.config.should_server_render func_name = JsRender.config.server_render_function.gsub('*', @component_name) server_code = <<-JS (function () { var serverStr = typeof #{func_name} === 'function' ? #{func_name}(#{@json_data}) : ''; return '<span id="#{@uuid}">' + serverStr + '</span>'; })() JS renderer_code = asset_finder.read_files(@component_name) context = ::ExecJS.compile(GLOBAL_CONTEXT + renderer_code) context.eval(server_code) rescue ExecJS::RuntimeError, ExecJS::ProgramError => error raise Errors::ServerRenderError::new(@component_name, @json_data, error) end |
#render_component ⇒ Object
24 25 26 27 28 29 |
# File 'lib/js_render/renderer.rb', line 24 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 |