Module: ActiveRecordNullObject::NullObjectSupport::ClassMethods

Defined in:
lib/activerecord_null_object/null_object_support.rb

Instance Method Summary collapse

Instance Method Details

#add_null_object_support(name, options = {}) ⇒ Object

Add null object support to the given accessor method.



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/activerecord_null_object/null_object_support.rb', line 10

def add_null_object_support(name, options = {}) #:nodoc:
  # Determine the class of the association.
  association_class_name = options[:class_name] || name.to_s.classify
  association_class = association_class_name.constantize
  null_class_name = "Null" + association_class_name

  # Determine the null class for this association.
  null_class = options[:null_object].to_s.classify.safe_constantize || null_class_name.safe_constantize

  unless null_class
    # Define the null class as an ancestor of the association class.
    null_class = Object.const_set(null_class_name, Class.new(association_class))
    null_class.class_eval do
      include ::Singleton
      include ::ActiveRecordNullObject::NullObject
    end
  end

  # Modify the "getter" of the relationship to return an
  # instance of the association's null object instead of returning nil.
  class_eval do
    define_method("#{name}".to_sym) do |*args|
      super(*args) || null_class.instance
    end
  end
end

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

Add a :null_object option to belongs_to.



38
39
40
41
42
43
44
45
46
47
# File 'lib/activerecord_null_object/null_object_support.rb', line 38

def belongs_to(name, scope = nil, **options)
  # args << options.except(:null_object)
  # Call the real belongs_to so that the association gets defined.
  super(name, scope, **options.except(:null_object))

  # Modify the association if need be.
  if options[:null_object]
    add_null_object_support(name, options)
  end
end

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

Add a :null_object option to has_one.



50
51
52
53
54
55
56
57
58
59
60
# File 'lib/activerecord_null_object/null_object_support.rb', line 50

def has_one(name, scope = nil, **options)
  # args = options.except(:null_object)

  # Call the real belongs_to so that the association gets defined.
  super(name, scope, **options.except(:null_object))

  # Modify the association if need be.
  if options[:null_object]
    add_null_object_support(name, options)
  end
end