Skip to content

Instantly share code, notes, and snippets.

@the-undefined
Last active August 29, 2015 14:02
Show Gist options
  • Save the-undefined/8df6e492b2be951ce34a to your computer and use it in GitHub Desktop.
Save the-undefined/8df6e492b2be951ce34a to your computer and use it in GitHub Desktop.
Implement the repository pattern with a strategy object (to swap out with an AR model)
class InMemoryStore
attr_accessor :result_set
def initialize
@result_set = []
end
def store(row)
!!(result_set << row)
end
def all
result_set
end
def where(criteria={})
return result_set unless criteria
selected_rows = result_set
criteria.each_pair do |attribute,value|
selected_rows = if value
selected_rows.select {|row| row[attribute] == value }
else
selected_rows.reject {|row| row[attribute] }
end
end
selected_rows
end
def count
result_set.count
end
end
class Repository
attr_reader :strategy
def initialize(strategy)
@strategy = strategy
end
def store(args)
!!strategy.store(args)
end
def where(args)
strategy.where(args)
end
def all
strategy.all
end
def count
strategy.count
end
end
Item = Class.new(Struct.new(:ref, :name))
a = Item.new(1, 'A')
b = Item.new(2, 'B')
c = Item.new(3, 'C')
repo = Repository.new(InMemoryStore.new)
repo.store(a)
repo.store(b)
repo.where(name: 'A') # => [#<struct Item ref=1, name="A">]
repo.where(ref: 2)[0].name # => "B"
repo.count # => 2
repo.all # => [#<struct Item ref=1, name="A">, #<struct Item ref=2, name="B">]
repo.store(c)
repo.where(ref: 3) # => [#<struct Item ref=3, name="C">]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment