Skip to content

Instantly share code, notes, and snippets.

@KamilLelonek
Last active September 15, 2022 16:05
Show Gist options
  • Save KamilLelonek/b28790ec22cfdaedd7cd to your computer and use it in GitHub Desktop.
Save KamilLelonek/b28790ec22cfdaedd7cd 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