Class: Repository::ActiveRecord

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

Defined Under Namespace

Classes: FakeScope

Instance Method Summary collapse

Methods inherited from Base

#filter, #find, #remove!, #remove_by_id!

Constructor Details

#initialize(model_klass, options = {}) ⇒ ActiveRecord

Returns a new instance of ActiveRecord.



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

def initialize(model_klass, options={})
  @model_klass        = model_klass
  @domain_model_klass = options[:domain_model_klass]
end

Instance Method Details

#create!(model_or_hash = {}) ⇒ Object



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

def create!(model_or_hash={})
  attrs = model_or_hash_as_attrs(model_or_hash)
  build_domain_model(model_klass.create!(attrs))
end

#execute_count(query) ⇒ Object



55
56
57
# File 'lib/repository/active_record.rb', line 55

def execute_count(query)
  apply_filters(model_klass, query[:filters]).count
end

#execute_find(query) ⇒ Object



47
48
49
50
51
52
53
# File 'lib/repository/active_record.rb', line 47

def execute_find(query)
  scope = apply_filters model_klass, query[:filters]
  scope = apply_sorts   scope,       query[:sorts]
  scope = apply_limit   scope,       query[:limit]
  scope = apply_offset  scope,       query[:offset]
  scope.all.map { |m| build_domain_model(m) }
end

#execute_remove!(query) ⇒ Object



59
60
61
# File 'lib/repository/active_record.rb', line 59

def execute_remove!(query)
  apply_filters(model_klass, query[:filters]).delete_all
end

#find_by_id(id) ⇒ Object



43
44
45
# File 'lib/repository/active_record.rb', line 43

def find_by_id(id)
  self.find.eq(model_klass.primary_key, id).first
end

#update!(model_or_id, attrs = {}) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/repository/active_record.rb', line 17

def update!(model_or_id, attrs={})
  attributes = attrs || {}
  case
  when model_or_id.is_a?(model_klass)
    if model_or_id.persisted?
      model_or_id.update_attributes(attributes)
      build_domain_model(model_or_id)
    else
      raise ArgumentError.new("Could not update record with id: #{model_or_id.send(primary_key)} because it does not exist")
    end
  when model_or_id.is_a?(domain_model_klass)
    id = model_or_id.send(primary_key)
    if model = model_klass.where(primary_key => id).first
      update!(model, model_or_id.attributes.merge(attributes))
    else
      raise ArgumentError.new("Could not update record with id: #{id} because it does not exist")
    end
  else
    if model = model_klass.where(primary_key => model_or_id).first
      update!(model, attributes)
    else
      raise ArgumentError.new("Could not update record with id: #{model_or_id} because it does not exist")
    end
  end
end