Rack::Utils.escape / unescape + CGI.escape/unescape/escapeHTML vs undefined method bytesize for nil

The official solution for this problem is to use e.g. CGI.escape thing.to_str,
my unofficial solution is to automate that 🙂

Code

# https://grosser.it/2012/08/16/rackutils-escape-unescape-cgi-escapeunescapeescapehtml-vs-undefined-method-bytesize-for-nil/
AUTOMATED_TO_STR_FOR_SAFE_BUFFER = <<-RUBY
  def METHOD_with_html_safe(object)
    if object.is_a?(ActiveSupport::SafeBuffer)
      METHOD(object.to_str)
    else
      METHOD_without_html_safe(object)
    end
  end
  alias_method_chain :METHOD, :html_safe
RUBY

# can be removed if
# Rack::Utils.escape "a & & %24".html_safe
# Rack::Utils.unescape "a & & %24".html_safe
# does not raise an error, must work with strings and symbols
Rack::Utils.class_eval do
  [:escape, :unescape].each do |method|
    eval AUTOMATED_TO_STR_FOR_SAFE_BUFFER.gsub("METHOD", method.to_s)
    module_function :"#{method}_without_html_safe"
    module_function method
  end
end

# can be removed if
# CGI.escape "a & & %24".html_safe
# CGI.unescape "a & & %24".html_safe
# CGI.unescapeHTML "a & & %24".html_safe
# does not raise an error, must work with strings and symbols
# (escapeHTML always works)
CGI.class_eval do
  class << self
    [:escape, :unescape, :unescapeHTML].each do |method|
      eval AUTOMATED_TO_STR_FOR_SAFE_BUFFER.gsub("METHOD", method.to_s)
    end
  end
end

Object.send :remove_const, :AUTOMATED_TO_STR_FOR_SAFE_BUFFER

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s