Skip to content

Instantly share code, notes, and snippets.

@danieldraper
Forked from KamilLelonek/1_brand.rb
Created August 27, 2019 01:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danieldraper/b45ac2987c04f204c71c4406f798e042 to your computer and use it in GitHub Desktop.
Save danieldraper/b45ac2987c04f204c71c4406f798e042 to your computer and use it in GitHub Desktop.
Repository pattern example in Ruby for Rails developers
module Storage
module Models
class Brand < ActiveRecord::Base; end
end
end
module Storage
module Entities
class BrandEntity
include ::Virtus.model
attribute :id, String
attribute :name, String
attribute :image, String
attribute :description, String
end
end
end
module Storage
module Repositories
module Repository
def initialize(orm_adapter)
@orm_adapter = orm_adapter
end
def load_all
orm_adapter.find_each.lazy.map &method(:map_record)
end
private
attr_reader :orm_adapter
end
end
end
require_relative 'repository'
module Storage
module Repositories
class BrandRepository
include Repository
def initialize(db = Models::Brand)
super
end
private
def map_record(record)
Entities::BrandEntity.new.tap do |brand|
brand.id = record.id
brand.name = record.name
brand.image = record.image
brand.description = record.description
end
end
end
end
end
module Storage
module QueryObjects
module QueryObject
def initialize(repository)
@repository = repository
end
private
attr_reader :repository
end
end
end
require_relative 'query_object'
module Storage
module QueryObjects
class GetAllBrands
include QueryObject
def initialize(repository = Repositories::BrandRepository.new)
super
end
def call
repository.load_all
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment