Module: HumanError::Persistable

Defined in:
lib/human_error/persistable.rb

Instance Method Summary collapse

Instance Method Details

#find(*ids) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/human_error/persistable.rb', line 23

def find(*ids)
  super
rescue ActiveRecord::RecordNotFound => e
  ids = case e.message
        when /\ACouldn't find .* without an ID\z/
          []
        when /\ACouldn't find .* with \'.*\'=(\d+)\z/
          [$1]
        when /\ACouldn't find all .* with \'.*\': ((?:\d+(?:, )?)+)\z/
          $1.split(', ')
        end

  raise HumanError::Errors::ResourceNotFoundError.new(
    resource_name:    human_error_resource_name,
    resource_id:      ids)
end

#human_error_resource_nameObject



40
41
42
43
44
45
46
47
48
49
# File 'lib/human_error/persistable.rb', line 40

def human_error_resource_name
  last_part_of_class_name = /::(\w+)\z/

  self.
    class.
    name[last_part_of_class_name, 1].
    underscore.
    humanize.
    downcase
end

#save!(*args) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/human_error/persistable.rb', line 3

def save!(*args)
  super
rescue ActiveRecord::InvalidForeignKey => e
  association_info_pattern = %r{DETAIL:  Key \((.*)_id\)=\((\d+)\)}
  association_name, association_id = e.message.
                                       match(association_info_pattern) \
                                       [1..-1]

  raise HumanError::Errors::AssociationError.new(
    resource_name:    human_error_resource_name,
    association_name: association_name,
    association_id:   association_id,
    attributes:       attributes)
rescue ActiveRecord::RecordInvalid, ActiveRecord::RecordNotSaved => e
  raise HumanError::Errors::ResourcePersistenceError.new(
    resource_name:    human_error_resource_name,
    attributes:       attributes,
    errors:           errors.full_messages)
end