Last active
July 26, 2017 05:14
-
-
Save rubyconvict/5b1ec981400c90c2ee06ff6e19f89390 to your computer and use it in GitHub Desktop.
NullObject
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Comment < ActiveRecord::Base | |
delegate :email, to: author, prefix: true, allow_nil: true | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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