Skip to content

Instantly share code, notes, and snippets.

@rubyconvict
Last active July 26, 2017 05:14
Show Gist options
  • Save rubyconvict/5b1ec981400c90c2ee06ff6e19f89390 to your computer and use it in GitHub Desktop.
Save rubyconvict/5b1ec981400c90c2ee06ff6e19f89390 to your computer and use it in GitHub Desktop.
NullObject
class Comment < ActiveRecord::Base
delegate :email, to: author, prefix: true, allow_nil: true
end
class NullObject
def present?; false; end
def empty?; true; end
def nil?; true; end
def !; true; end
def tap; self; end
def to_a; []; end
def to_s; ""; end
def to_f; 0.0; end
def to_i; 0; end
def method_missing(*args, &block)
if args.first.to_s[/\?/]
raise NoMethodError, <<-HEREDOC.squish
#{args.inspect}
on: #{to_yaml}
HEREDOC
end
nil
end
end
module NullObjectPersistable
extend ActiveSupport::Concern
included do
def self.mimics_persistence_from(real_model_class)
@real_model_class = real_model_class
end
def self.real_model_class
@real_model_class
end
def self.table_name
@real_model_class.to_s.tableize
end
def self.primary_key
'id'
end
end
def real_model_class
self.class.real_model_class
end
def id
end
def [](*)
end
def is_a?(klass)
if klass == real_model_class
true
else
super
end
end
def destroyed?
false
end
def new_record?
false
end
def persisted?
false
end
end
class NullUser
include NullObjectPersistable
mimics_persistence_from User
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment