Class: Looksy::Repository

Inherits:
Object
  • Object
show all
Defined in:
lib/looksy/repository.rb

Instance Method Summary collapse

Constructor Details

#initialize(klass, cache) ⇒ Repository

Returns a new instance of Repository.



3
4
5
6
# File 'lib/looksy/repository.rb', line 3

def initialize(klass, cache)
  @klass = klass
  @cache = cache
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/looksy/repository.rb', line 24

def method_missing(method, *args, &block)
  if match = Looksy::DynamicFindMatch.match(method)
    super unless all_attributes_exist?(match.attributes)

    attributes = extract_attributes(match.attributes) do |attribute|
      args[match.attributes.index(attribute)]
    end

    result = all.send(match.finder) do |record|
      record_attributes = extract_attributes(match.attributes) do |attribute|
        record.send(attribute)
      end

      record_attributes == attributes
    end

    match.extractor ? result.send(match.extractor) : result
  else
    super
  end
end

Instance Method Details

#allObject



8
9
10
# File 'lib/looksy/repository.rb', line 8

def all
  @cache.fetch(@klass.cache_key, @klass.cache_options) { @klass.all }
end

#find_by_id(id) ⇒ Object



20
21
22
# File 'lib/looksy/repository.rb', line 20

def find_by_id(id)
  all.find { |record| record.id == id.to_i }
end

#firstObject



12
13
14
# File 'lib/looksy/repository.rb', line 12

def first
  all.first
end

#lastObject



16
17
18
# File 'lib/looksy/repository.rb', line 16

def last
  all.last
end