Module: BetterHtml::TestHelper::SafeLodashTester

Defined in:
lib/better_html/test_helper/safe_lodash_tester.rb

Defined Under Namespace

Classes: Tester

Constant Summary collapse

SAFETY_TIPS =
<<~EOF
  -----------

  The javascript snippets listed above do not appear to be escaped properly
  in their context. Here are some tips:

  Always use lodash's escape syntax inside a html tag:
    <a href="[%= value %]">
             ^^^^

  Always use JSON.stringify() for html attributes which contain javascript, like 'onclick',
  or twine attributes like 'data-define', 'data-context', 'data-eval', 'data-bind', etc:
    <div onclick="[%= JSON.stringify(value) %]">
                      ^^^^^^^^^^^^^^

  Never use <script> tags inside lodash template.
    <script type="text/javascript">
    ^^^^^^^

  -----------
EOF

Instance Method Summary collapse

Instance Method Details

#assert_lodash_safety(data, **options) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/better_html/test_helper/safe_lodash_tester.rb', line 33

def assert_lodash_safety(data, **options)
  buffer = ::Parser::Source::Buffer.new(options[:filename] || "(buffer)")
  buffer.source = data
  tester = Tester.new(buffer, **options)

  message = +""
  tester.errors.each do |error|
    message << <<~EOL
      On line #{error.location.line}
      #{error.message}
      #{error.location.line_source_with_underline}\n
    EOL
  end

  message << SAFETY_TIPS

  assert_predicate(tester.errors, :empty?, message)
end