Class: Repositor::Repo::ActiveRecordAdapter

Inherits:
Base
  • Object
show all
Extended by:
InstanceMethodsFilter
Defined in:
lib/repositor/repo/active_record.rb

Constant Summary collapse

TYPE =
'Repo'.freeze

Instance Attribute Summary

Attributes included from InstanceMethodsFilter

#allowed_methods

Attributes inherited from Base

#model

Instance Method Summary collapse

Methods included from InstanceMethodsFilter

allow_instance_methods

Methods inherited from Base

#initialize

Constructor Details

This class inherits a constructor from Repositor::Base

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object

All methods that have instance object as first argument will be redirected to itself with all other arguments ‘some_repo.new_record?(record)` same as `record.new_record?` But gives you more control under persistence process



30
31
32
33
34
35
36
37
38
39
# File 'lib/repositor/repo/active_record.rb', line 30

def method_missing(method, *args)
  # Break if first argument was not a model record
  return unless args[0].instance_of? model

  # Super if allowed_methods not defined or in not included in array
  am = self.class.allowed_methods
  super if am.nil? || !am.include?(method)

  resend_method(method, args)
end

Instance Method Details

#find_or_initialize(id, friendly: false) ⇒ Object

Common find process with supporting of friendly_id params



13
14
15
16
17
# File 'lib/repositor/repo/active_record.rb', line 13

def find_or_initialize(id, friendly: false)
  friendly ? friendly_find(id) : model.find(id)
rescue ::ActiveRecord::RecordNotFound
  model.new
end

#friendly_find(slugged_id) ⇒ Object

Support for ‘friendly_id` gem out of box



20
21
22
# File 'lib/repositor/repo/active_record.rb', line 20

def friendly_find(slugged_id)
  model.friendly.find(slugged_id)
end

#resend_method(method, args) ⇒ Object



41
42
43
44
45
46
47
48
49
50
# File 'lib/repositor/repo/active_record.rb', line 41

def resend_method(method, args)
  # All except first argumet is a record params
  params = args.drop(1)

  if params.any?
    args[0].public_send(method, params)
  else
    args[0].public_send(method)
  end
end