Last active
October 6, 2017 08:11
-
-
Save pjg/0700d4f90a93d41aad0bc77a2cbc79fc to your computer and use it in GitHub Desktop.
rom-mapper problem with reverse relationship
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-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