Skip to content

Instantly share code, notes, and snippets.

@cheald
Created November 25, 2012 03:36
Show Gist options
  • Select an option

  • Save cheald/4142314 to your computer and use it in GitHub Desktop.

Select an option

Save cheald/4142314 to your computer and use it in GitHub Desktop.
module ActiveSupport
module FastSafeBuffer
[
:capitalize, :chomp, :chop, :delete, :downcase, :gsub, :lstrip,
:next, :reverse, :rstrip, :slice, :squeeze, :strip, :sub,
:succ, :swapcase, :tr, :tr_s, :upcase, :prepend
].each do |unsafe_method|
if String.new.respond_to? unsafe_method
module_eval <<-EVAL
def #{unsafe_method}!(*)
@html_safe = false
super
end
EVAL
end
end
def [](*args)
return super if args.size < 2
super.add_safety(self)
end
def safe_concat(value)
raise ActiveSupport::SafeBuffer::SafeConcatError unless html_safe?
concat(value)
end
def safe!
@html_safe = true
end
def initialize_copy(other)
super
safe! if other.html_safe?
end
def clone_empty
self[0, 0].add_safety(self)
end
def concat(value)
if html_safe? and value.html_safe?
super(value)
else
super(ERB::Util.h(value))
end
end
alias << concat
def +(other)
dup.concat(other)
end
def dup
super.add_safety(self, true)
end
def html_safe?
!!@html_safe
end
def to_s
self
end
def encode_with(coder)
coder.represent_scalar nil, to_str
end
def to_yaml(*args)
return super() if defined?(YAML::ENGINE) && !YAML::ENGINE.syck?
to_str.to_yaml(*args)
end
end
end
class String
def add_safety(from = nil, force = false)
unless @_extended_html_safe and !force
@_extended_html_safe = true
self.extend ::ActiveSupport::FastSafeBuffer
safe! if from == true or from.html_safe?
end
self
end
def html_safe
add_safety(true)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment