Module: RailsConsoleAi::DiffHelper

Defined in:
app/helpers/rails_console_ai/diff_helper.rb

Instance Method Summary collapse

Instance Method Details

#render_json_diff(left_obj, right_obj, **opts) ⇒ Object

Convenience for diffing two tag arrays / hashes as JSON.



29
30
31
32
33
34
35
# File 'app/helpers/rails_console_ai/diff_helper.rb', line 29

def render_json_diff(left_obj, right_obj, **opts)
  render_text_diff(
    JSON.pretty_generate(left_obj || []),
    JSON.pretty_generate(right_obj || []),
    **opts
  )
end

#render_text_diff(left, right, left_label: 'Before', right_label: 'After') ⇒ Object

Render a side-by-side line diff of two strings.

Returns HTML-safe markup with <span class=“diff-add”> and <span class=“diff-del”> rows. Uses a tiny LCS-based algorithm so we avoid taking on the diff-lcs gem as a runtime dependency.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'app/helpers/rails_console_ai/diff_helper.rb', line 11

def render_text_diff(left, right, left_label: 'Before', right_label: 'After')
  a = (left || '').split("\n", -1)
  b = (right || '').split("\n", -1)
  ops = diff_ops(a, b)

  rows = []
  ops.each do |op, l_line, r_line|
    rows << render_diff_row(op, l_line, r_line)
  end

  html = +%(<table class="diff-table">)
  html << %(<thead><tr><th>#{ERB::Util.h(left_label)}</th><th>#{ERB::Util.h(right_label)}</th></tr></thead>)
  html << %(<tbody>) << rows.join << %(</tbody>)
  html << %(</table>)
  html.respond_to?(:html_safe) ? html.html_safe : html
end