Skip to content

Instantly share code, notes, and snippets.

@AMHOL
Created September 6, 2016 13:57
Show Gist options
  • Save AMHOL/945e307b355be409c9a32cfb187ad5fa to your computer and use it in GitHub Desktop.
Save AMHOL/945e307b355be409c9a32cfb187ad5fa to your computer and use it in GitHub Desktop.
require 'json'
require 'uri'
require 'net/http'
gemfile(true) do
gem 'anima'
gem 'rom'
gem 'rom-http'
gem 'rom-repository'
end
module ROM
module MyAdapter
class Dataset < ROM::HTTP::Dataset
default_request_handler ->(dataset) do
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), request|
request[header.to_s] = value
end
response = http.request(request)
end
default_response_handler ->(response, dataset) do
Array([JSON.parse(response.body, symbolize_names: true)]).flatten
end
end
class Gateway < ROM::HTTP::Gateway; end
class Relation < ROM::HTTP::Relation
adapter :my_adapter
end
module Commands
class Create < ROM::HTTP::Commands::Create
adapter :my_adapter
end
class Update < ROM::HTTP::Commands::Update
adapter :my_adapter
end
class Delete < ROM::HTTP::Commands::Delete
adapter :my_adapter
end
end
end
end
ROM.register_adapter(:my_adapter, ROM::MyAdapter)
configuration = ROM::Configuration.new(:my_adapter, {
uri: 'http://jsonplaceholder.typicode.com',
headers: {
Accept: 'application/json'
}
})
class User
ATTRIBUTES = %i(id name username email phone website).freeze
include Anima.new(*ATTRIBUTES)
end
class Users < ROM::Relation[:my_adapter]
dataset :users
register_as :users
schema do
attribute :id, ROM::Types::Int
attribute :name, ROM::Types::String
attribute :username, ROM::Types::String
attribute :email, ROM::Types::String
attribute :phone, ROM::Types::String
attribute :website, ROM::Types::String
end
view(:base, User::ATTRIBUTES) do
self
end
def by_id(id)
with_path(id.to_s)
end
end
configuration.register_relation(Users)
container = ROM.container(configuration)
class UserRepository < ROM::Repository[:users]
def find(id)
users.by_id(id).as(User).one!
end
end
user_repo = UserRepository.new(container)
user_repo.find(1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment