Module: Moribus::AliasAssociation::ClassMethods

Defined in:
lib/moribus/alias_association.rb

Overview

Class methods for ActiveRecord::Base

Instance Method Summary collapse

Instance Method Details

#alias_association(alias_name, association_name) ⇒ Object

Aliases association reflection in ActiveRecord’s (internal) reflections hash and association-specific methods. See module description for example.



24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/moribus/alias_association.rb', line 24

def alias_association(alias_name, association_name)
  if reflection = reflect_on_association(association_name)
    # Use Rails 4.1.x+ behavior, if available:
    if ActiveRecord::Reflection.respond_to? :add_reflection then
      ActiveRecord::Reflection.add_reflection self, alias_name, reflection
    else
      # Rails 4.0.x behavior:
      reflections[alias_name] = reflections[association_name]
    end
    alias_association_methods(alias_name, reflection)
    reflection
  end
end

#belongs_to(name, scope = nil, options = {}) ⇒ Object

Allows :alias option to alias belongs_to association



39
40
41
42
43
44
45
46
# File 'lib/moribus/alias_association.rb', line 39

def belongs_to(name, scope = nil, options = {})
  options = scope if scope.is_a?(Hash)

  alias_name = options.delete(:alias)
  reflection = super(name, scope, options)
  alias_association(alias_name, name) if alias_name
  reflection
end

#has_many(name, scope = nil, options = {}, &extension) ⇒ Object

Allows :alias option to alias has_many association



49
50
51
52
53
54
55
56
# File 'lib/moribus/alias_association.rb', line 49

def has_many(name, scope = nil, options = {}, &extension)
  options = scope if scope.is_a?(Hash)

  alias_name = options.delete(:alias)
  reflection = super(name, scope, options, &extension)
  alias_association(alias_name, name) if alias_name
  reflection
end

#has_one(name, scope = nil, options = {}) ⇒ Object

Allows :alias option to alias has_one association



59
60
61
62
63
64
65
66
# File 'lib/moribus/alias_association.rb', line 59

def has_one(name, scope = nil, options = {})
  options = scope if scope.is_a?(Hash)

  alias_name = options.delete(:alias)
  reflection = super(name, scope, options)
  alias_association(alias_name, name) if alias_name
  reflection
end