Module: Fixjour::Definitions

Included in:
Fixjour
Defined in:
lib/fixjour/definitions.rb

Instance Method Summary collapse

Instance Method Details

#define_create(builder) ⇒ Object

Defines the create_* method



11
12
13
14
15
16
17
# File 'lib/fixjour/definitions.rb', line 11

def define_create(builder)
  define_method("create_#{builder.name}") do |*args|
    model = send("new_#{builder.name}", *args)
    model.save!
    model
  end
end

#define_new(builder, &block) ⇒ Object

Defines the new_* method



4
5
6
7
8
# File 'lib/fixjour/definitions.rb', line 4

def define_new(builder, &block)
  define_method("new_#{builder.name}") do |*args|
    Generator.new(builder.klass, block).call(self, args.extract_options!.symbolize_keys!)
  end
end

#define_valid_attributes(builder) ⇒ Object

Defines the valid_*_attributes method



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
# File 'lib/fixjour/definitions.rb', line 20

def define_valid_attributes(builder)
  define_method("valid_#{builder.name}_attributes") do |*args|
    record = send("new_#{builder.name}", *args)
    valid_attributes = record.attributes
    valid_attributes.delete_if { |key, value| value.nil? }

    transfer_singular_ids = proc { |reflection|
      if associated = record.send(reflection.name)
        associated.new_record? && associated.save!
        key = reflection.options[:foreign_key] || reflection.name.to_s + '_id'
        valid_attributes[key] = associated.id
      end
    }

    transfer_plural_ids = proc { |reflection|
      associated = record.send(reflection.name)
      if associated.length > 0
        associated.each { |rec| rec.new_record? && rec.save! }
        key = (reflection.options[:foreign_key] || reflection.name).to_s
        key.gsub!(/_ids?$/, '')
        valid_attributes[key.singularize + '_ids'] = associated.map(&:id)
        valid_attributes.delete(reflection.name)
      end
    }

    if builder.klass.respond_to?(:reflect_on_all_associations)
      builder.klass.reflect_on_all_associations(:has_one).each(&transfer_singular_ids)
      builder.klass.reflect_on_all_associations(:belongs_to).each(&transfer_singular_ids)
      builder.klass.reflect_on_all_associations(:has_many).each(&transfer_plural_ids)
    elsif builder.klass.respond_to?(:associations)
      # MongoMapper doesnt support reflections on associations.
      # This little check allows almost identical support
      # for MongoMapper even with the associations.
      builder.klass.associations.each do |name, association|
        if [:one, :belongs_to].include?(association.type)
          transfer_singular_ids.call(association)
        elsif association.type == :many
          transfer_plural_ids.call(association)
        end
      end
    end

    valid_attributes.stringify_keys!
    valid_attributes.make_indifferent!
    valid_attributes
  end
end