Skip to content

Instantly share code, notes, and snippets.

@pjg
Last active October 6, 2017 08:11
Show Gist options
  • Save pjg/0700d4f90a93d41aad0bc77a2cbc79fc to your computer and use it in GitHub Desktop.
Save pjg/0700d4f90a93d41aad0bc77a2cbc79fc to your computer and use it in GitHub Desktop.

Revisions

  1. pjg revised this gist Jul 30, 2016. 1 changed file with 2 additions and 2 deletions.
    4 changes: 2 additions & 2 deletions rom-mapper.rb
    Original file line number Diff line number Diff line change
    @@ -43,7 +43,7 @@ class Preprocessor < ROM::Mapper
    end

    module Repository
    class Author
    class Authors
    class << self
    def all
    @@authors ||= preprocessor.call raw_authors
    @@ -70,7 +70,7 @@ def gateway
    end
    end

    authors = Repository::Author.all
    authors = Repository::Authors.all

    p authors
    p authors.first.name
  2. pjg revised this gist Jul 30, 2016. No changes.
  3. pjg created this gist Jul 30, 2016.
    82 changes: 82 additions & 0 deletions rom-mapper.rb
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,82 @@
    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 Author
    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::Author.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)