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.5"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(base) ⇒ Object



201
202
203
# File 'lib/activerecord/null.rb', line 201

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

Instance Method Details

#Null(inherit = self, class_name: :Null, **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)

    The attributes to assign to the null object



159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/activerecord/null.rb', line 159

def Null(inherit = self, class_name: :Null, **assignments, &)
  if inherit.is_a?(Hash)
    assignments = inherit
    inherit = self
  end

  null_class = create_null_class(inherit, assignments, singleton: true)
  null_class.class_eval(&) if block_given?

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

#Void(inherit = self, class_name: :Void, **assignments) ⇒ Object

Define a Void class for the given class. Unlike Null, Void objects are not singletons and can be instantiated multiple times with different attribute values.

Examples:

class Product < ApplicationRecord
  Void do
    def display_name = "Product: #{name}"
  end
end

product1 = Product.void(name: "Widget")
product2 = Product.void(name: "Gadget")

Parameters:

  • inherit (Class) (defaults to: self)

    The class from which the Void object inherits attributes

  • assignments (Hash)

    The default attributes to assign to void objects



188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/activerecord/null.rb', line 188

def Void(inherit = self, class_name: :Void, **assignments, &)
  if inherit.is_a?(Hash)
    assignments = inherit
    inherit = self
  end

  void_class = create_null_class(inherit, assignments, singleton: false)
  void_class.class_eval(&) if block_given?

  inherit.const_set(class_name, void_class)
  inherit.define_singleton_method(:void) { |attributes = {}| void_class.new(attributes) }
end