Skip to content

Instantly share code, notes, and snippets.

@SleeplessByte
Created July 27, 2015 13:23
Show Gist options
  • Save SleeplessByte/c1697f3ce8cc70ba7444 to your computer and use it in GitHub Desktop.
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
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
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