Class: Formatter::JSON

Inherits:
Formatter
  • Object
show all
Defined in:
app/formatters/json_formatter.rb

Instance Method Summary collapse

Instance Method Details

#apply_templateObject

Hook for setting available options using a template. See the template documentation for the available options and their format.



8
9
10
11
# File 'app/formatters/json_formatter.rb', line 8

def apply_template
  apply_table_format_template(template.table)
  apply_grouping_format_template(template.grouping)
end

#build_group_bodyObject

Creates the group body. Since group data is a table, just uses the Table controller.



57
58
59
# File 'app/formatters/json_formatter.rb', line 57

def build_group_body
  render_table data, options.to_hash
end

#build_group_headerObject

Renders the header for a group using the group name.



50
51
52
# File 'app/formatters/json_formatter.rb', line 50

def build_group_header
  output << "  \"#{data.name}\":"
end

#build_grouping_bodyObject

Generates the body for a grouping. Iterates through the groups and renders them using the group controller.



64
65
66
67
68
69
70
# File 'app/formatters/json_formatter.rb', line 64

def build_grouping_body
  arr = []
  data.each do |_,group|                     
    arr << render_group(group, options)
  end
  output << arr.join(",\n")
end

#build_row(data = self.data) ⇒ Object

Renders individual rows for the table.



36
37
38
39
40
41
42
43
44
45
46
# File 'app/formatters/json_formatter.rb', line 36

def build_row(data = self.data)
  values = data.to_a
  keys = self.data.column_names.to_a
  hash = {}
  values.each_with_index do |val, i|
    key = (keys[i] || i).to_s
    hash[key] = val
  end
  line = hash.to_json.to_s
  output << "  #{line}"
end

#build_table_bodyObject

Uses the Row controller to build up the table body.



21
22
23
24
25
26
27
# File 'app/formatters/json_formatter.rb', line 21

def build_table_body
  data.each_with_index do |row, i|
    output << ",\n" if i > 0 
    build_row(row)
  end
  output << "\n"
end

End the JSON



30
31
32
# File 'app/formatters/json_formatter.rb', line 30

def build_table_footer
  output << "]"
end

#build_table_headerObject

Start the JSON



15
16
17
# File 'app/formatters/json_formatter.rb', line 15

def build_table_header
  output << "[\n"
end