Module: Pageflow::RenderJsonHelper

Overview

Helpers for rendering JSON seed data.

Constant Summary collapse

ESCAPED_CHARS =
{
  "\u2028" => '\u2028',
  "\u2029" => '\u2029',
  '</' => '<\/'
}.freeze
ESCAPED_CHARS_REGEX =
%r{</|[\u2028\u2029]}u

Instance Method Summary collapse

Instance Method Details

#render_html_partial(*args) ⇒ Object

Render the given partial with format HTML, independent from currently rendered format. Can be used to render HTML to be included in a JSON response. Takes same parameters as Rails normal render method.



59
60
61
62
63
# File 'app/helpers/pageflow/render_json_helper.rb', line 59

def render_html_partial(*args)
  render_with_format(:html) do
    render(*args)
  end
end

#render_json(&block) ⇒ Object

Yields to given block with JBuilder object and returns rendered JSON as string.

Since:

  • 15.1



33
34
35
36
37
# File 'app/helpers/pageflow/render_json_helper.rb', line 33

def render_json(&block)
  render_with_format(:json) do
    JbuilderTemplate.encode(self, &block)
  end
end

#render_json_partial(*args) ⇒ Object

Render the given partial with format JSON, independent from currently rendered format. Can be used together with #sanitize_json to render JSON to be included in an HTML script tag. Takes same parameters as JBuilder’s partial! method.



21
22
23
24
25
26
27
# File 'app/helpers/pageflow/render_json_helper.rb', line 21

def render_json_partial(*args)
  render_with_format(:json) do
    render_json { |json|
      json.partial!(*args)
    }.html_safe
  end
end

#render_json_seed(records, options = {}) ⇒ Object

Renders ‘image_files/_image_file.json.jbuilder` when given a collection of `ImageFile` records.



6
7
8
9
10
11
12
13
14
15
# File 'app/helpers/pageflow/render_json_helper.rb', line 6

def render_json_seed(records, options = {})
  if records.respond_to?(:to_model)
    name = records.to_model.class.model_name.to_s.split('::').last.underscore.downcase
    render_json_partial(['pageflow/editor', name.pluralize, name.singularize] * '/', name.singularize.to_sym => records)
  else
    return '[]'.html_safe if records.empty?
    name = records.first.to_model.class.model_name.to_s.split('::').last.underscore.downcase
    render_json_partial(['pageflow/editor', name.pluralize, name.singularize] * '/', :collection => records, :as => name.singularize.to_sym)
  end
end

#sanitize_json(json) ⇒ Object

Make JSON string safe for embedding in HTML script tag. Escape whitespace characters that are allowed in JSON but not allowed in HTML. Make sure closing script tag in JSON text is not interpreted as closing tag of the surrounding script tag.



51
52
53
# File 'app/helpers/pageflow/render_json_helper.rb', line 51

def sanitize_json(json)
  json.gsub(ESCAPED_CHARS_REGEX, ESCAPED_CHARS)
end