Module: ActiveRecord::Null

Defined in:
lib/activerecord/null.rb,
lib/activerecord/null/mimic.rb,
lib/activerecord/null/version.rb

Overview

Extend any ActiveRecord class with this module to add a null object. Add it to your primary abstract class.

Examples:

class ApplicationRecord < ActiveRecord::Base
  primary_abstract_class
  extend ActiveRecord::Null
end

Defined Under Namespace

Modules: Mimic

Constant Summary collapse

VERSION =
"0.1.1"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(base) ⇒ Object



62
63
64
# File 'lib/activerecord/null.rb', line 62

def self.extended(base)
  base.define_method(:null?) { false }
end

Instance Method Details

#Null(inherit = self, assignments = {}) ⇒ Object

Define a Null class for the given class.

Examples:

class Business < ApplicationRecord
  Null do
    def name = "None"
  end
end

Business.null # => #<Business::Null:0x0000000000000000>
Business.null.name # => "None"

class User < ApplicationRecord
  Null([:name, :team_name] => "Unknown")
end

User.null.name # => "Unknown"
User.null.team_name # => "Unknown"

Parameters:

  • inherit (Class) (defaults to: self)

    The class from which the Null object inherits attributes

  • assignments (Array) (defaults to: {})

    The attributes to assign to the null object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/activerecord/null.rb', line 36

def Null(inherit = self, assignments = {}, &)
  if inherit.is_a?(Hash)
    assignments = inherit
    inherit = self
  end
  null_class = Class.new do
    include ::ActiveRecord::Null::Mimic
    mimics inherit

    include Singleton
  end
  null_class.class_eval(&) if block_given?

  nil_assignments = inherit.attribute_names
  if assignments.any?
    assignments.each do |attributes, value|
      nil_assignments -= attributes
      null_class.define_attribute_methods(attributes, value:)
    end
  end
  null_class.define_attribute_methods(nil_assignments)
  inherit.const_set(:Null, null_class)

  inherit.define_singleton_method(:null) { null_class.instance }
end