Интеграция ханами-модели в проект ruby
Структура моего приложения:
.
├── config
│ ├── boot.rb
│ └── environment.rb
├── Gemfile
├── Gemfile.lock
├── lib
│ ├── entities
│ │ └── account.rb
│ └── repositories
│ └── account_repository.rb
└── README.md
Gemfile:
source 'https://rubygems.org'
gem 'pg', '~> 1.1'
gem 'dotenv'
gem 'byebug'
gem 'hanami-model'
конфиг /environment.rb:
require 'bundler/setup'
require 'hanami/model'
require 'dotenv/load'
class App
class << self
def boot
Mutex.new.synchronize do
Hanami::Model.configure do
adapter :sql, ENV['DATABASE_URL']
end.load!
end
end
end
end
конфиг / boot.rb:
require_relative './environment'
App.boot
Библиотека / компании / account.rb:
require 'hanami/model'
require_relative '../repositories/account_repository'
class Account < Hanami::Entity
end
Библиотека / Хранилище /account_repository.rb:
require 'hanami/model'
require_relative '../entities/account'
class AccountRepository < Hanami::Repository
self.relation = :accounts
end
в консоли я запускаю следующий код и получаю ошибку:
irb -I .
irb(main):001:0> require 'config/boot'
=> true
irb(main):002:0> require 'lib/repositories/account_repository'
=> true
irb(main):003:0> rep = AccountRepository.new
Traceback (most recent call last):
6: from /home/mvalitov/.asdf/installs/ruby/2.5.1/bin/irb:11:in `<main>'
5: from (irb):3
4: from (irb):3:in `new'
3: from /home/mvalitov/.asdf/installs/ruby/2.5.1/lib/ruby/gems/2.5.0/gems/hanami-model-1.3.2/lib/hanami/repository.rb:420:in `initialize'
2: from /home/mvalitov/.asdf/installs/ruby/2.5.1/lib/ruby/gems/2.5.0/gems/rom-repository-1.4.0/lib/rom/repository/root.rb:62:in `initialize'
1: from /home/mvalitov/.asdf/installs/ruby/2.5.1/lib/ruby/gems/2.5.0/gems/rom-3.3.3/lib/rom/registry.rb:30:in `fetch'
ArgumentError (key cannot be nil)
Что я делаю неправильно? если вы поместите весь код сущности и репозитории в один файл, код будет работать без ошибок.
2 ответа
Проблема в порядке загрузки.
Вот примечание о строгом порядке в документации:
При использовании адаптера sql вы должны потребовать hanami / model / sql перед Hanami::Model.load! вызывается, чтобы отношения загружались правильно.
Источник: https://github.com/hanami/model#mapping
Следовательно, в вашем случае необходимо запустить после всех объявлений.
Подробно:
Если вы поместите весь свой код в один файл, вы увидите различия:
# run.rb
require 'bundler/setup'
require 'hanami/model'
require 'dotenv/load'
class App
class << self
def boot
Mutex.new.synchronize do
Hanami::Model.configure do
adapter :sql, 'postgresql://postgres:12345@localhost:5432/mame-challenge_development'
path '/home/mifrill/Documents/source/hamani-bug'
end.load!
end
end
end
end
App.boot
class AccountRepository < Hanami::Repository
self.relation = :accounts
end
class Account < Hanami::Entity
end
AccountRepository.new
gems/rom-3.3.3/lib/rom/registry.rb:30:in `fetch': key cannot be nil (ArgumentError)
Двигаться
App.boot
после определений репозитория и сущности, например:
require 'bundler/setup'
require 'hanami/model'
require 'dotenv/load'
class App
class << self
def boot
Mutex.new.synchronize do
Hanami::Model.configure do
adapter :sql, 'postgresql://postgres:12345@localhost:5432/mame-challenge_development'
path '/home/mifrill/Documents/source/hamani-bug'
end.load!
end
end
end
end
class AccountRepository < Hanami::Repository
self.relation = :accounts
end
class Account < Hanami::Entity
end
App.boot
AccountRepository.new
ruby run.rb
{:accounts=>#<ROM::Relation[Accounts] name=accounts dataset=#<Sequel::Postgres::Dataset: "SELECT * FROM \"accounts\"">>
Итак, попробуйте потребовать файл репозитория перед
load!
решать:
config/boot.rb
:
require_relative './environment'
require_relative '../lib/repositories/account_repository'
App.boot
irb -I .
require 'config/boot'
rep = AccountRepository.new
...
{:accounts=>#<ROM::Relation[Accounts] name=accounts dataset=#<Sequel::Postgres::Dataset: "SELECT * FROM \"accounts\"">>}
Вам не хватает "корневой" конфигурации / опций (я не знаю, так как я не использую Hanami).
Как я это нашел?
Глядя на трассировку стека:
- https://github.com/hanami/model/blob/master/lib/hanami/repository.rb#L420
- https://github.com/rom-rb/rom-repository/blob/master/lib/rom/repository/root.rb#L62
- https://github.com/rom-rb/rom/blob/master/core/lib/rom/registry.rb#L30
- Где выдается ошибка: https://github.com/rom-rb/rom/blob/master/core/lib/rom/registry.rb#L71
fetch
имеет псевдоним:[]
(все ссылки на последние, потому что я ленивый:))