This very-light skeleton demonstrates on way to connect a merchant to their items. Things to notice:
repository_integration_test.rbhas the one test. Run it withruby test/repository_integration_test.rb- It creates an instance of
SalesEngine. Look at thesales_engine.rbto see that the newSalesEngineinitializes both aMerchantRepositoryand aItemRepository, but most importantly that it passes those objectsselfwhich is a reference to theSalesEngineinstance. - The initializers of both
MerchantRepositoryandItemRepositorystore that reference asengineso they can later reach back up to the SalesEngine they came from - When
MerchantRepositorycreatesMerchantinstances (line 9 in themerchantsmethod), it again passesselfin as a parameter. Thatselfis theMerchantRepositoryinstance. - The test calls the
.itemsmethod on aMerchantinstance. Inmerchant.rbsee how theitemsmethod reaches up to therepository(the parent instance ofMerchantRepository) and asks for theitems_forand passes itself up to the repo. - In
MerchantRepository#items_for, the repo reaches up to theengineand calls theitems_for_merchant_idand passes in the ID number of themerchantparameter - In
SalesEngine, theitems_for_merchant_idmethod just callsfind_all_by_merchant_idon theitem_repositoryinstance it instantiated in the initialize ItemRepository#find_all_by_merchant_idactually does the select, and passes the results back to theSalesEngine, which passes them back to theMerchantRepository, which passes them back to theMerchantinstance, which passes them back to the test.- The test assertion succeeds, having found three items.
No problem, right? :)