Sha256: 494dc7789217d9666e8730c05c30586e980924853b11fa0b25ec43ca3eb28304

Contents?: true

Size: 986 Bytes

Versions: 5

Compression:

Stored size: 986 Bytes

Contents

# frozen-string-literal: true

#
class Roda
  module RodaPlugins
    # The h plugin adds an +h+ instance method that will HTML
    # escape the input and return it.
    #
    # The following example will return "<foo>" as the body.
    #
    #   plugin :h
    #
    #   route do |r|
    #     h('<foo>')
    #   end
    module H
      # A Hash of entities and their escaped equivalents,
      # to be escaped by h().
      ESCAPE_HTML = {
        "&" => "&amp;".freeze,
        "<" => "&lt;".freeze,
        ">" => "&gt;".freeze,
        "'" => "&#x27;".freeze,
        '"' => "&quot;".freeze,
      }.freeze

      # A Regexp of HTML entities to match for escaping.
      ESCAPE_HTML_PATTERN = Regexp.union(*ESCAPE_HTML.keys)

      module InstanceMethods
        # HTML escape the input and return the escaped version.
        def h(string)
          string.to_s.gsub(ESCAPE_HTML_PATTERN){|c| ESCAPE_HTML[c] }
        end
      end
    end

    register_plugin(:h, H)
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
roda-2.23.0 lib/roda/plugins/h.rb
roda-2.22.0 lib/roda/plugins/h.rb
roda-2.21.0 lib/roda/plugins/h.rb
roda-2.20.0 lib/roda/plugins/h.rb
roda-2.19.0 lib/roda/plugins/h.rb