Class: AutoBuild::Association

Inherits:
Object
  • Object
show all
Defined in:
lib/auto_build/association.rb

Overview

Public: Represents an ActiveRecord association. Takes care of adding the hooks to the models.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model, association_name, options = {}) ⇒ Association

Public: Creates a new Association.

model - The ActiveRecord model (not the instance!). association_name - Name of the association you will want to

add the callback to.

options - The Hash options used to the number of

records (default = {}):
:count  - An Integer that specifies the number of
          records to create.
:append - Boolean, defines if you only want one record
          at the end of the array. False by default.
          Equivalent to :count => 1.

‘has_one` associations **don’t** receive any options.

For ‘has_many` associations, if the user doesn’t pass any options, the default will be to add one new record if no other records exist yet.

Examples

Association.new(User, :photo)

Association.new(User, :projects, :append => true)

Association.new(User, :projects, :count => 3)

Association.new(user, :photo)
# => Error! You want to pass the class, no the instance

Raises AutoBuildError if you pass the :count and :append options at the same time.



47
48
49
50
51
52
53
54
# File 'lib/auto_build/association.rb', line 47

def initialize(model, association_name, options={})
  @model = model
  @association_name = association_name
  @options = options
  @type = model.reflect_on_association(association_name).macro

  validate_options
end

Instance Attribute Details

#association_nameObject (readonly)

Public: Returns the name of the association.



8
9
10
# File 'lib/auto_build/association.rb', line 8

def association_name
  @association_name
end

#modelObject (readonly)

Public: Returns the model this association works on.



6
7
8
# File 'lib/auto_build/association.rb', line 6

def model
  @model
end

#optionsObject (readonly)

Public: Returns the options that were passed in when created.



10
11
12
# File 'lib/auto_build/association.rb', line 10

def options
  @options
end

#typeObject (readonly)

Public: Returns the type (macro) of association (e.g. has_one, :has_many).



13
14
15
# File 'lib/auto_build/association.rb', line 13

def type
  @type
end

Instance Method Details

#add_hookObject

Public: Adds the callback to the objects.

It will choose the correct hook based on the value of ‘type`.



59
60
61
62
63
64
65
# File 'lib/auto_build/association.rb', line 59

def add_hook
  if [:has_one, :belongs_to].include?(type)
    HasOneHook.new(model, association_name).attach
  else
    HasManyHook.new(model, association_name, options).attach
  end
end