travis-api/lib/travis/api/app/responders/json.rb
Piotr Sarnacki 61142c7cf6 Return 404 unless we can find API builder for resource
In order to protect us from rendering a resource simply converted to
json, without processing it with API data class, this commit changes
JSON responder behavior to render 404 if we can't find associated data
class. The only exception to that rule is when resource is already a
Hash, meaning that it was processed before - we sometimes return for
example simple Hash responses like { result: true }.

The Hash exception could allow to accidentally pass resource.as_json to
responder, but in travis-ci/travis-support@124b8b6 I disabled default
as_json method on AR::Base classes, so the risk of such mistake is
lowered.
2013-03-24 19:49:28 +01:00

53 lines
1.2 KiB
Ruby

class Travis::Api::App
module Responders
class Json < Base
include Helpers::Accept
def apply?
super && !resource.is_a?(String) && !resource.nil? && accepts_log?
end
def apply
halt result.to_json if result
end
private
def accepts_log?
return true unless resource.is_a?(Log)
chunked = accept_params[:chunked]
chunked ? !resource.aggregated_at : true
end
def result
builder ? builder.new(resource, params).data : basic_type_resource
end
def builder
if defined?(@builder)
@builder
else
@builder = Travis::Api.builder(resource, { :version => version }.merge(options))
end
end
def accept_params
(options[:accept].params || {}).symbolize_keys
end
def version
options[:accept].version || Travis::Api::App::Helpers::Accept::DEFAULT_VERSION
end
def params
(request.params || {}).merge(accept_params)
end
def basic_type_resource
resource if resource.is_a?(Hash)
end
end
end
end