class Cocooned::AssociationBuilder

Attributes

association[RW]
form[RW]
options[RW]

Public Class Methods

new(form, association, options = {}) click to toggle source
# File lib/cocooned/association_builder.rb, line 7
def initialize(form, association, options = {})
  self.form = form
  self.association = association
  self.options = options.reverse_merge(force_non_association_create: false, wrap_object: false)
end

Public Instance Methods

build_object() click to toggle source
# File lib/cocooned/association_builder.rb, line 13
def build_object
  model = reflection ? build_with_reflection : build_without_reflection
  model = @options[:wrap_object].call(model) if @options[:wrap_object].respond_to?(:call)
  model
end
plural_name() click to toggle source
# File lib/cocooned/association_builder.rb, line 23
def plural_name
  association.to_s.pluralize
end
singular_name() click to toggle source
# File lib/cocooned/association_builder.rb, line 19
def singular_name
  association.to_s.singularize
end

Private Instance Methods

build_with_conditions() click to toggle source
# File lib/cocooned/association_builder.rb, line 63
def build_with_conditions
  conditions = reflection.respond_to?(:conditions) ? reflection.conditions.flatten : []
  reflection.klass.new(*conditions)
end
build_with_reflection() click to toggle source
# File lib/cocooned/association_builder.rb, line 36
def build_with_reflection
  return build_with_conditions if should_use_conditions?

  # Assume ActiveRecord or compatible
  # We use a clone of the current form object to not link
  # object together (even if unsaved)
  dummy = form.object.dup
  model = if reflection.collection?
            dummy.send(association).build
          else
            dummy.send("build_#{association}")
          end
  model = model.dup if model.frozen?
  model
end
build_without_reflection() click to toggle source
# File lib/cocooned/association_builder.rb, line 52
def build_without_reflection
  methods = %W[build_#{plural_name} build_#{singular_name}].select { |m| form.object.respond_to?(m) }
  raise "Association #{association} doesn't exist on #{form.object.class}" unless methods.any?

  form.object.send(methods.first)
end
reflection() click to toggle source
# File lib/cocooned/association_builder.rb, line 29
def reflection
  @reflection ||= begin
    klass = form.object.class
    klass.respond_to?(:reflect_on_association) ? klass.reflect_on_association(association) : nil
  end
end
should_use_conditions?() click to toggle source
# File lib/cocooned/association_builder.rb, line 59
def should_use_conditions?
  reflection.class.name.starts_with?('Mongoid::') || @options[:force_non_association_create]
end