Class: ActiveRecord::AssociatedObject

Inherits:
Object
  • Object
show all
Defined in:
lib/active_record/associated_object/version.rb,
lib/active_record/associated_object.rb

Defined Under Namespace

Modules: ObjectAssociation Classes: Railtie

Constant Summary collapse

VERSION =
"0.7.1"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(record) ⇒ AssociatedObject

Returns a new instance of AssociatedObject.



37
38
39
# File 'lib/active_record/associated_object.rb', line 37

def initialize(record)
  @record = record
end

Instance Attribute Details

#recordObject (readonly)

Returns the value of attribute record.



34
35
36
# File 'lib/active_record/associated_object.rb', line 34

def record
  @record
end

Class Method Details

.extension(&block) ⇒ Object



18
19
20
# File 'lib/active_record/associated_object.rb', line 18

def extension(&block)
  record_klass.class_eval(&block)
end

.inherited(klass) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/active_record/associated_object.rb', line 3

def inherited(klass)
  record_klass   = klass.module_parent
  record_name    = klass.module_parent_name.demodulize.underscore
  attribute_name = klass.to_s.demodulize.underscore.to_sym

  unless record_klass.respond_to?(:descends_from_active_record?) && record_klass.descends_from_active_record?
    raise ArgumentError, "#{record_klass} isn't valid; can only associate with ActiveRecord::Base subclasses"
  end

  klass.alias_method record_name, :record
  klass.define_singleton_method(:record_klass)   { record_klass }
  klass.define_singleton_method(:attribute_name) { attribute_name }
  klass.delegate :record_klass, :attribute_name, to: :class
end

.method_missing(method) ⇒ Object



25
26
27
28
29
30
31
# File 'lib/active_record/associated_object.rb', line 25

def method_missing(method, ...)
  if !record_klass.respond_to?(method) then super else
    record_klass.public_send(method, ...).then do |value|
      value.respond_to?(:each) ? value.map(&attribute_name) : value&.public_send(attribute_name)
    end
  end
end

.respond_to_missing?Boolean

Returns:

  • (Boolean)


22
# File 'lib/active_record/associated_object.rb', line 22

def respond_to_missing?(...) = record_klass.respond_to?(...) || super

Instance Method Details

#==(other) ⇒ Object



41
42
43
# File 'lib/active_record/associated_object.rb', line 41

def ==(other)
  other.is_a?(self.class) && id == other.id
end