Class: ApplicationRecord

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
app/models/application_record.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.aggregate_of(association) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
# File 'app/models/application_record.rb', line 50

def self.aggregate_of(association)
  class_eval do
    define_method(:rebuild!) do |children|
      transaction do
        self.send(association).all_except(children).delete_all
        self.update! association => children
        children.each &:save!
      end
      reload
    end
  end
end

.all_except(others) ⇒ Object



15
16
17
18
19
20
21
# File 'app/models/application_record.rb', line 15

def self.all_except(others)
  if others.present?
    where.not(id: [others.map(&:id)])
  else
    all
  end
end

.defaults(&block) ⇒ Object



4
5
6
7
# File 'app/models/application_record.rb', line 4

def self.defaults(&block)
  after_initialize :defaults, if: :new_record?
  define_method :defaults, &block
end

.name_model_as(other) ⇒ Object



9
10
11
12
13
# File 'app/models/application_record.rb', line 9

def self.name_model_as(other)
  define_singleton_method :model_name do
    other.model_name
  end
end

.numbered(*associations) ⇒ Object



63
64
65
66
67
68
69
70
71
72
# File 'app/models/application_record.rb', line 63

def self.numbered(*associations)
  class_eval do
    associations.each do |it|
      define_method("#{it}=") do |e|
        e.merge_numbers!
        super(e)
      end
    end
  end
end

.update_or_create!(attributes) ⇒ Object



74
75
76
77
78
# File 'app/models/application_record.rb', line 74

def self.update_or_create!(attributes)
  obj = first || new
  obj.update!(attributes)
  obj
end

Instance Method Details

#saveObject



23
24
25
26
27
28
# File 'app/models/application_record.rb', line 23

def save(*)
  super
rescue => e
  self.errors.add :base, e.message
  self
end

#save_and_notify!Object



38
39
40
41
42
# File 'app/models/application_record.rb', line 38

def save_and_notify!
  save!
  notify!
  self
end

#save_and_notify_changes!Object



30
31
32
33
34
35
36
# File 'app/models/application_record.rb', line 30

def save_and_notify_changes!
  if changed?
    save_and_notify!
  else
    save!
  end
end

#update_and_notify!(data) ⇒ Object



44
45
46
47
48
# File 'app/models/application_record.rb', line 44

def update_and_notify!(data)
  update! data
  notify!
  self
end