Sha256: d53855fb038483b4d7004f07b0fe8fdc3075264bade847af094e8c86d8f74e08

Contents?: true

Size: 1.44 KB

Versions: 88

Compression:

Stored size: 1.44 KB

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
      begin
        require 'cgi/escape'
        unless CGI.respond_to?(:escapeHTML) # work around for JRuby 9.1
          # :nocov:
          CGI = Object.new
          CGI.extend(defined?(::CGI::Escape) ? ::CGI::Escape : ::CGI::Util)
          # :nocov:
        end

        module InstanceMethods
          # HTML escape the input and return the escaped version.
          def h(string)
            CGI.escapeHTML(string.to_s)
          end
        end
      rescue LoadError
        # :nocov:

        # A Hash of entities and their escaped equivalents,
        # to be escaped by h().
        ESCAPE_HTML = {
          "&" => "&amp;".freeze,
          "<" => "&lt;".freeze,
          ">" => "&gt;".freeze,
          "'" => "&#39;".freeze,
          '"' => "&quot;".freeze,
        }.freeze

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

        module InstanceMethods
          def h(string)
            string.to_s.gsub(ESCAPE_HTML_PATTERN){|c| ESCAPE_HTML[c] }
          end
        end
        # :nocov:
      end
    end

    register_plugin(:h, H)
  end
end

Version data entries

88 entries across 88 versions & 1 rubygems

Version Path
roda-3.86.0 lib/roda/plugins/h.rb
roda-3.85.0 lib/roda/plugins/h.rb
roda-3.84.0 lib/roda/plugins/h.rb
roda-3.83.0 lib/roda/plugins/h.rb
roda-3.82.0 lib/roda/plugins/h.rb
roda-3.81.0 lib/roda/plugins/h.rb
roda-3.79.0 lib/roda/plugins/h.rb
roda-3.78.0 lib/roda/plugins/h.rb
roda-3.77.0 lib/roda/plugins/h.rb
roda-3.76.0 lib/roda/plugins/h.rb
roda-3.75.0 lib/roda/plugins/h.rb
roda-3.74.0 lib/roda/plugins/h.rb
roda-3.73.0 lib/roda/plugins/h.rb
roda-3.72.0 lib/roda/plugins/h.rb
roda-3.71.0 lib/roda/plugins/h.rb
roda-3.70.0 lib/roda/plugins/h.rb
roda-3.69.0 lib/roda/plugins/h.rb
roda-3.68.0 lib/roda/plugins/h.rb
roda-3.67.0 lib/roda/plugins/h.rb
roda-3.66.0 lib/roda/plugins/h.rb