class NestedAttr::NestedAttributesStrategy

Public Instance Methods

association(runner) click to toggle source
# File lib/nested_attr.rb, line 24
def association(runner)
  runner.run
end
result(evaluation) click to toggle source
# File lib/nested_attr.rb, line 28
def result(evaluation)

  evaluation.object.tap do |instance|
  
    evaluation.notify(:after_build, instance) 
    
    return attributes(instance)
  end
end

Private Instance Methods

attributes(instance) click to toggle source
# File lib/nested_attr.rb, line 42
def attributes(instance)
@created_model||=[]
  
  unless instance.instance_variables.include? :@attributes then return {} end  
  if @created_model.include? instance.class then return {} end

  @created_model << instance.class
  
  attrs = instance.attributes.delete_if do |k, _|
    ( %w(id type created_at updated_at).include?(k) or k.end_with?("_id") ) 
  end
  

  nested_reflections_belongs_to(instance).each do |ref|
    attrs.merge!("#{ref.name}" => attributes(instance.send(ref.name)))
  end

  nested_reflections_has_many(instance).each do |ref|
    if @@has_many_attributes.include? ref.name
      attrs.merge!("#{ref.name}_attributes" => instance.send(ref.name).each_with_index.map do |nested_obj,i|
        {i.to_s => attributes(nested_obj)}
      end [0])
    else
      attrs.merge!("#{ref.name.to_s.singularize}_ids" => instance.send(ref.name).each.map do |nested_obj|
        nested_obj.id.to_s
      end)  
    end

  end
  
  nested_reflections_has_and_belongs_to_many(instance).each do |ref|
    #puts ref.name
    #puts "+++"
    #puts @@allowd_nested_attributes[0].class
    #puts @@allowd_nested_attributes.include? ref.name
    #puts "---"

    if @@has_many_attributes.include? ref.name
      attrs.merge!("#{ref.name}_attributes" => instance.send(ref.name).each_with_index.map do |nested_obj,i|
        {i.to_s => attributes(nested_obj)}
      end [0])
    else
      attrs.merge!("#{ref.name.to_s.singularize}_ids" => instance.send(ref.name).each.map do |nested_obj|
        nested_obj.id.to_s
      end)  
    end
  end




  

  instance.delete 
  
  attrs
end
nested_reflections_belongs_to(instance) click to toggle source
# File lib/nested_attr.rb, line 114
def nested_reflections_belongs_to(instance)  
  instance.class.reflections.values.select do |ref|
    ref.macro == :belongs_to && instance.respond_to?("#{ref.name}")
  end
end
nested_reflections_has_and_belongs_to_many(instance) click to toggle source
# File lib/nested_attr.rb, line 102
def nested_reflections_has_and_belongs_to_many(instance)
  instance.class.reflections.values.select do |ref|
    ref.macro == :has_and_belongs_to_many 
  end
end
nested_reflections_has_many(instance) click to toggle source
# File lib/nested_attr.rb, line 108
def nested_reflections_has_many(instance)
  instance.class.reflections.values.select do |ref|
    ref.macro == :has_many && instance.respond_to?("#{ref.name}_attributes=")
  end
end