Module: JsonApiToolbox::Postable

Defined in:
lib/postable.rb

Class Method Summary collapse

Class Method Details

.association_class(model, key) ⇒ Object



18
19
20
21
22
23
24
25
# File 'lib/postable.rb', line 18

def self.association_class(model, key)
  association = model.reflect_on_all_associations.find do |association|
    association.name.to_s == key.to_s
  end
  return false unless association
  class_name = (association.options.symbolize_keys[:class_name] || key)
  ActiveSupport::Inflector.singularize(class_name).camelize.constantize
end

.check_child_association(value, key, model, child_model) ⇒ Object



27
28
29
30
31
32
33
# File 'lib/postable.rb', line 27

def self.check_child_association(value, key, model, child_model)
  if value.is_a?(Hash) && !model.has_attribute?(key)
    self.normalize_post(value, child_model)
  else
    value
  end
end

.normalize_post(hash, model) ⇒ Object



5
6
7
8
9
10
11
12
13
14
# File 'lib/postable.rb', line 5

def self.normalize_post(hash, model)
  associations = model.reflect_on_all_associations.map(&:name)
  normalized_hash = hash.map do |key, value|
    child_model = self.association_class(model, key) if value.is_a? Hash
    key = associations.include?(key.to_sym) ? "#{key}_attributes" : key
    hash_value = check_child_association(value, key, model, child_model)
    [key, hash_value]
  end
  Hash[normalized_hash]
end