Method: Effective::Resources::Instance#instance_attributes

Defined in:
app/models/effective/resources/instance.rb

#instance_attributes(only: nil, except: nil) ⇒ Object

called by effective_trash and effective_logging



14
15
16
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'app/models/effective/resources/instance.rb', line 14

def instance_attributes(only: nil, except: nil)
  return {} unless instance.present?

  # Build up our only and except
  only = Array(only).map(&:to_sym)
  except = Array(except).map(&:to_sym) + BLACKLIST

  # Simple Attributes
  attributes = { attributes: instance.attributes.symbolize_keys }

  attributes[:attributes] = attributes[:attributes].except(*except) if except.present?
  attributes[:attributes] = attributes[:attributes].slice(*only) if only.present?

  # Collect to_s representations of all belongs_to associations
  belong_tos.each do |association|
    next if except.present? && except.include?(association.name)
    next unless only.blank? || only.include?(association.name)

    attributes[association.name] = instance.send(association.name).to_s
  end

  # Grab the instance attributes of each nested resource
  nested_resources.each do |association|
    next if except.present? && except.include?(association.name)
    next unless only.blank? || only.include?(association.name)

    next if association.options[:through]

    attributes[association.name] ||= {}

    Array(instance.send(association.name)).each_with_index do |child, index|
      next unless child.present?

      resource = Effective::Resource.new(child)
      attributes[association.name][index] = resource.instance_attributes(only: only, except: except)
    end
  end

  (action_texts + has_ones).each do |association|
    next if except.present? && except.include?(association.name)
    next unless only.blank? || only.include?(association.name)

    attributes[association.name] = instance.send(association.name).to_s
  end

  has_manys.each do |association|
    next if except.present? && except.include?(association.name)
    next unless only.blank? || only.include?(association.name)

    next if BLACKLIST.include?(association.name)
    attributes[association.name] = instance.send(association.name).map { |obj| obj.to_s }
  end

  has_and_belongs_to_manys.each do |association|
    next if except.present? && except.include?(association.name)
    next unless only.blank? || only.include?(association.name)

    attributes[association.name] = instance.send(association.name).map { |obj| obj.to_s }
  end

  attributes.delete_if { |_, value| value.blank? }
end