Class: RailsBestPractices::Core::ModelAssociations

Inherits:
Object
  • Object
show all
Defined in:
lib/rails_best_practices/core/model_associations.rb

Overview

Model associations container.

Instance Method Summary collapse

Constructor Details

#initializeModelAssociations

Returns a new instance of ModelAssociations.



6
7
8
# File 'lib/rails_best_practices/core/model_associations.rb', line 6

def initialize
  @associations = {}
end

Instance Method Details

#add_association(model_name, association_name, association_meta, association_class = nil) ⇒ Object

Parameters:

  • model (String)

    name

  • association (String)

    name

  • association (String)

    meta, has_many, has_one, belongs_to and has_and_belongs_to_many

  • association (String)

    class name



15
16
17
18
# File 'lib/rails_best_practices/core/model_associations.rb', line 15

def add_association(model_name, association_name, association_meta, association_class=nil)
  @associations[model_name] ||= {}
  @associations[model_name][association_name] = {"meta" => association_meta, "class_name" => association_class || association_name.classify}
end

#each(&block) ⇒ Object

delegate each to @associations.



41
42
43
# File 'lib/rails_best_practices/core/model_associations.rb', line 41

def each(&block)
  @associations.each { |model, model_associations| yield model, model_associations }
end

#get_association(model_name, association_name) ⇒ Hash

Get a model association.

Parameters:

  • model (String)

    name

  • association (String)

    name

Returns:

  • (Hash)

    => association_meta, “class_name” => association_class



25
26
27
28
# File 'lib/rails_best_practices/core/model_associations.rb', line 25

def get_association(model_name, association_name)
  associations = @associations[model_name]
  associations and associations[association_name]
end

#get_association_class_name(table_name, association_name) ⇒ String

Get association’s class name

Parameters:

  • table (String)

    name

  • association_name (String)

Returns:

  • (String)

    association’s class name



50
51
52
53
54
# File 'lib/rails_best_practices/core/model_associations.rb', line 50

def get_association_class_name(table_name, association_name)
  associations = @associations.select { |model, model_associations| model.gsub("::", "").tableize == table_name }.values.first and
    association_meta = associations.select { |name, meta| name == association_name }.values.first and
    association_meta["class_name"]
end

#is_association?(model_name, association_name) ⇒ Boolean

If it is a model’s association.

Parameters:

  • model (String)

    name

  • association (String)

    name

Returns:

  • (Boolean)

    true if it is the model’s association



35
36
37
38
# File 'lib/rails_best_practices/core/model_associations.rb', line 35

def is_association?(model_name, association_name)
  associations = @associations[model_name]
  associations && associations[association_name]
end