class Rack::AdequateJson
Constants
- VERSION
Attributes
app[R]
headers[R]
root[R]
status[R]
target_param[R]
Public Class Methods
new(app , options={})
click to toggle source
# File lib/rack/adequate_json/adequate_json.rb, line 5 def initialize(app , options={}) @app = app @root = options.fetch(:root, nil) @target_param = options.fetch(:target_param, "fields") end
Public Instance Methods
call(env)
click to toggle source
# File lib/rack/adequate_json/adequate_json.rb, line 11 def call(env) call_and_setup(env) if content_type_json? && filter_fields [ status, headers, response_stream { |b| filter_json_body(b) } ] else [status, headers, response_stream] end end
Protected Instance Methods
call_and_setup(env)
click to toggle source
# File lib/rack/adequate_json/adequate_json.rb, line 22 def call_and_setup(env) @status, @headers, @response = app.call(env) @request = request(env) @filter_fields = nil end
content_type_json?()
click to toggle source
# File lib/rack/adequate_json/adequate_json.rb, line 69 def content_type_json? @headers["Content-Type"].include?("json") end
filter_fields()
click to toggle source
# File lib/rack/adequate_json/adequate_json.rb, line 41 def filter_fields if params[target_param] && !params[target_param].strip.empty? @filter_fields ||= params[target_param].split(',').map(&:strip) else nil end end
filter_json_body(body)
click to toggle source
# File lib/rack/adequate_json/adequate_json.rb, line 28 def filter_json_body(body) json_body = JSON.parse(body) data = root ? json_body[root] : json_body if data.is_a?(Hash) slice_data!(data, filter_fields) elsif data.is_a?(Array) data.each{ |data| slice_data!(data, filter_fields) } end json_body.to_json end
params()
click to toggle source
# File lib/rack/adequate_json/adequate_json.rb, line 65 def params @request.params end
request(env)
click to toggle source
# File lib/rack/adequate_json/adequate_json.rb, line 61 def request(env) Rack::Request.new(env) end
response_stream(&block)
click to toggle source
# File lib/rack/adequate_json/adequate_json.rb, line 49 def response_stream(&block) body = [] @response.each do |body_part| body << ( block ? block.call(body_part) : body_part) end body end
slice_data!(data, fields)
click to toggle source
# File lib/rack/adequate_json/adequate_json.rb, line 57 def slice_data!(data, fields) data.select!{|k,v| fields.include?(k) } if fields end