lib/hyperdrive/hateoas.rb in hyperdrive-0.0.15 vs lib/hyperdrive/hateoas.rb in hyperdrive-0.0.16
- old
+ new
@@ -3,43 +3,59 @@
module Hyperdrive
class HATEOAS
extend Hyperdrive::Values
def self.call(env)
+ @env = env
if hyperdrive.resources.empty? || env['PATH_INFO'] != '/'
raise Hyperdrive::Errors::NotFound
end
- endpoints = hyperdrive.resources.map do |_,resource|
- resource.to_hash
- end
+ [200, headers, [body]]
+ end
- api = {
- _links: { self: { href: '/' } },
- name: hyperdrive.config[:name],
- description: hyperdrive.config[:description],
- vendor: hyperdrive.config[:vendor],
- resources: endpoints
- }
+ private
- media_types = %w(hal+json json).map do |media_type|
+ def self.media_types
+ %w(hal+json json).map do |media_type|
"application/vnd.#{hyperdrive.config[:vendor]}+#{media_type}"
+ end + %w(application/hal+json application/json)
+ end
+
+ def self.content_type
+ @env['hyperdrive.accept'].best_of(media_types)
+ end
+
+ def self.headers
+ {
+ 'Access-Control-Allow-Origin' => '*',
+ 'Access-Control-Allow-Methods' => 'GET, HEAD, OPTIONS',
+ 'Allow' => 'GET, HEAD, OPTIONS',
+ 'Content-Type' => content_type
+ }
+ end
+
+ def self.endpoints
+ hyperdrive.resources.map do |_,resource|
+ resource.to_hash
end
+ end
- media_types += %w(application/hal+json application/json)
- content_type = env['hyperdrive.accept'].best_of(media_types)
- body = if content_type =~ /json$/
- MultiJson.dump(api)
- else
- raise Errors::NotAcceptable.new(env['HTTP_ACCEPT'])
- end
+ def self.response
+ {
+ _links: { self: { href: '/' } },
+ name: hyperdrive.config[:name],
+ description: hyperdrive.config[:description],
+ vendor: hyperdrive.config[:vendor],
+ resources: endpoints
+ }
+ end
- status = 200
- headers = {}
- headers['Access-Control-Allow-Origin'] = '*'
- headers['Access-Control-Allow-Methods'] = 'GET, HEAD, OPTIONS'
- headers['Allow'] = 'GET, HEAD, OPTIONS'
- headers['Content-Type'] = content_type
- [status, headers, [body]]
+ def self.body
+ if content_type =~ /json$/
+ MultiJson.dump(response)
+ else
+ raise Errors::NotAcceptable.new(@env['HTTP_ACCEPT'])
+ end
end
end
end