Created
August 14, 2015 20:16
-
-
Save solnic/215f5f18479b5635c67c to your computer and use it in GitHub Desktop.
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 'rom' | |
require 'rom-http' | |
require 'rom-repository' | |
require 'json' | |
require 'uri' | |
require 'net/http' | |
class RequestHandler | |
def call(dataset) | |
uri = URI(dataset.uri) | |
uri.path = "/#{dataset.name}/#{dataset.path}" | |
uri.query = URI.encode_www_form(dataset.params) | |
http = Net::HTTP.new(uri.host, uri.port) | |
request_klass = Net::HTTP.const_get(ROM::Inflector.classify(dataset.request_method)) | |
request = request_klass.new(uri.request_uri) | |
dataset.headers.each_with_object(request) do |(header, value), req| | |
req[header.to_s] = value | |
end | |
http.request(request) | |
end | |
end | |
class ResponseHandler | |
def call(response, dataset) | |
Array([JSON.parse(response.body)]).flatten | |
end | |
end | |
ROM.use :auto_registration | |
ROM.setup(:http, { | |
uri: 'http://jsonplaceholder.typicode.com', | |
headers: { | |
Accept: 'application/json' | |
}, | |
request_handler: RequestHandler.new, | |
response_handler: ResponseHandler.new | |
}) | |
class Posts < ROM::Relation[:http] | |
dataset :posts | |
use :view | |
use :key_inference | |
view(:base, ["userId", "id", "title", "body"]) do | |
self | |
end | |
def by_id(id) | |
with_path(id.to_s) | |
end | |
end | |
class PostRepository < ROM::Repository::Base | |
relations :posts | |
def by_id(id) | |
posts.by_id(id) | |
end | |
end | |
container = ROM.finalize.env | |
post_repo = PostRepository.new(container) | |
puts post_repo.by_id(1).to_a.inspect | |
# [#<ROM::Struct[Post] userId=1 id=1 title="sunt aut facere repellat provident occaecati excepturi optio reprehenderit" body="quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit mo | |
lestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto">] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment