Module: Rails::Patch::Json::Encode

Defined in:
lib/rails/patch/json/encode/version.rb,
lib/rails/patch/json/encode.rb

Constant Summary collapse

VERSION =
"0.1.0"

Class Method Summary collapse

Class Method Details

.patch_base_classesObject

Code from devblog.agworld.com.au/post/42586025923/the-performance-of-to-json-in-rails-sucks-and-theres essentially reversing Rails’ hard-coded call to ActiveSupport::JSON.encode



25
26
27
28
29
30
31
32
33
# File 'lib/rails/patch/json/encode.rb', line 25

def self.patch_base_classes
  [Object, Array, FalseClass, Float, Hash, Integer, NilClass, String, TrueClass].each do |klass|
    klass.class_eval do
      def to_json(opts = {})
        MultiJson::dump(self.as_json(opts), opts)
      end
    end
  end
end

.patch_renderersObject

Use multi_json instead of Rails’ to_json method (which calls ActiveSupport::JSON) when ‘render :json => @obj` is called.



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/rails/patch/json/encode.rb', line 6

def self.patch_renderers
  ::ActionController::Renderers.module_eval do
    # Override
    add :json do |json, options|
      json = MultiJson::dump(json.as_json(options), options) unless json.kind_of?(String)

      if options[:callback].present?
        self.content_type ||= Mime::JS
        "#{options[:callback]}(#{json})"
      else
        self.content_type ||= Mime::JSON
        json
      end
    end
  end
end