Skip to content

Instantly share code, notes, and snippets.

@pjg pjg/rom-mapper.rb
Last active Oct 6, 2017

Embed
What would you like to do?
rom-mapper problem with reverse relationship
require 'rom-mapper'
class BigDecimal
def inspect
format("#<BigDecimal:%x %s>", object_id, to_s('F'))
end
end
class Gateway
def get_authors
[
{
'name' => 'John Doe',
'books' => [
{
'title' => 'First book',
'price' => '15.99',
},
{
'title' => 'Second book',
'price' => '18.99',
},
]
}
]
end
end
class Preprocessor < ROM::Mapper
symbolize_keys true
model name: 'Author'
attribute :name
embedded :books, type: :array do
model name: 'Book'
attribute :title
attribute :price, type: :decimal
end
end
module Repository
class Authors
class << self
def all
@@authors ||= preprocessor.call raw_authors
end
def find_by_name name
all.detect { |author| author.name == name }
end
private
def preprocessor
Preprocessor.build
end
def raw_authors
@@raw_authors ||= gateway.get_authors
end
def gateway
@@gateway ||= Gateway.new
end
end
end
end
authors = Repository::Authors.all
p authors
p authors.first.name
p authors.first.books.first.author.name
# outputs:
# [#<Author:0x007fc30e328060 @name="John Doe", @books=[#<Book:0x007fc30e328560 @title="First book", @price=#<BigDecimal:3fe18719438c 15.99>>, #<Book :0x007fc30e3281f0 @title="Second book", @price=#<BigDecimal:3fe1871941d4 18.99>>]>]
# "John Doe"
# rom-mapper.rb:77:in `<main>': undefined method `author' for #<Book:0x007fc30e328560> (NoMethodError)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.