Last active
December 10, 2015 02:38
-
-
Save kenkeiter/4368501 to your computer and use it in GitHub Desktop.
Fix grape's incredible brokenness.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'sinatra/base' | |
require 'sinatra/namespace' | |
# You may need multi_json | |
class API < Sinatra::Base | |
# Respond to all errors with JSON | |
error do | |
content_type :json | |
e = env['sinatra.error'] | |
MultiJson.dump({:result => 'error', :message => e.message}) | |
end | |
# Define some content helpers. | |
helpers do | |
def json(response) | |
content_type :json | |
if response.respond_to?(:entity) or response.respond_to?(:as_json) | |
body MultiJson.dump(response.as_json) | |
else | |
body MultiJson.dump(response) | |
end | |
end | |
# Moved (mostly) from Grape. Hate you, Grape. | |
def present(object, options = {}) | |
content_type :json | |
entity_class = options.delete(:with) | |
object.class.ancestors.each do |potential| | |
entity_class ||= (settings[:representations] || {})[potential] | |
end | |
entity_class ||= object.class.const_get(:Entity) if object.class.const_defined?(:Entity) | |
root = options.delete(:root) | |
representation = if entity_class | |
entity_class.represent(object, embeds.merge(options)) | |
else | |
object | |
end | |
representation = { root => representation } if root | |
body representation.as_json.to_json | |
end | |
end | |
namespace '/api/sheet' do | |
post '/do-something-terrible' do | |
raise 'Fail massively!' | |
end | |
get '/' do | |
@sheet = Sheet.get(1) | |
json @sheet # will call #entity -> #as_json on it, if defined. | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment