class ActiveSupport::JSON::Encoding::ActiveSupportEncoder

Constants

ESCAPED_CHARS
ESCAPE_REGEX_WITHOUT_HTML
ESCAPE_REGEX_WITH_HTML

Attributes

options[R]

Public Class Methods

escape(string) click to toggle source
# File lib/active_support/json/encoding/active_support_encoder.rb, line 76
def escape(string)
  string = string.encode ::Encoding::UTF_8, undef: :replace
  regex = Encoding.escape_html_entities_in_json ? ESCAPE_REGEX_WITH_HTML : ESCAPE_REGEX_WITHOUT_HTML
  %("#{string.gsub regex, ESCAPED_CHARS}")
end
new(options = nil) click to toggle source
# File lib/active_support/json/encoding/active_support_encoder.rb, line 15
def initialize(options = nil)
  @options = options || {}
  @seen = Set.new
end

Public Instance Methods

as_json(value, use_options = true) click to toggle source

like encode, but only calls as_json, without encoding to string.

# File lib/active_support/json/encoding/active_support_encoder.rb, line 28
def as_json(value, use_options = true)
  check_for_circular_references(value) do
    use_options ? value.as_json(options_for(value)) : value.as_json
  end
end
encode(value, use_options = true) click to toggle source
# File lib/active_support/json/encoding/active_support_encoder.rb, line 20
def encode(value, use_options = true)
  check_for_circular_references(value) do
    jsonified = use_options ? value.as_json(options_for(value)) : value.as_json
    jsonified.respond_to?(:encode_json) ? jsonified.encode_json(self) : encode(jsonified, false)
  end
end
escape(string) click to toggle source
# File lib/active_support/json/encoding/active_support_encoder.rb, line 44
def escape(string)
  self.class.escape(string)
end
options_for(value) click to toggle source
# File lib/active_support/json/encoding/active_support_encoder.rb, line 34
def options_for(value)
  if value.is_a?(Array) || value.is_a?(Hash)
    # hashes and arrays need to get encoder in the options, so that
    # they can detect circular references.
    options.merge(encoder: self)
  else
    options.dup
  end
end

Private Instance Methods

check_for_circular_references(value) { || ... } click to toggle source
# File lib/active_support/json/encoding/active_support_encoder.rb, line 84
def check_for_circular_references(value)
  unless @seen.add?(value.__id__)
    raise CircularReferenceError, 'object references itself'
  end
  yield
ensure
  @seen.delete(value.__id__)
end