Created
July 27, 2015 13:23
-
-
Save SleeplessByte/c1697f3ce8cc70ba7444 to your computer and use it in GitHub Desktop.
Use same format, prefix, formatter and error handler for multiple grape api's
This file contains hidden or 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
module Namespace | |
module API | |
extend ActiveSupport::Concern | |
included do | |
format :xml | |
prefix :api | |
formatter :xml, xml_formatter | |
rescue_from :all do |e| | |
error!( | |
{ | |
error: "#{e.class} error", | |
message: e.message | |
}, | |
e.try( :status ) || 500 | |
) | |
end | |
helpers do | |
def current_user | |
#... | |
end | |
def authenticate! | |
error!( '401 Unauthorized', 401 ) unless current_user | |
end | |
end | |
end | |
class_methods do | |
def xml_formatter | |
lambda { |object,env| | |
if object.is_a? Hash | |
# removes hashie from collection | |
object[object.keys.first].as_json.to_xml :root => object.keys.first, :skip_types => true | |
elsif object.is_a? String | |
# what. no. | |
object | |
else | |
# removes hash from single | |
object.to_xml | |
end | |
} | |
end | |
end | |
end | |
end |
This file contains hidden or 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
module Route | |
class API < Grape::API | |
include Univercity::API | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment