Skip to content

Instantly share code, notes, and snippets.

@Neener54
Last active August 29, 2015 14:07
Show Gist options
  • Save Neener54/fc98611e5b64bbd41712 to your computer and use it in GitHub Desktop.
Save Neener54/fc98611e5b64bbd41712 to your computer and use it in GitHub Desktop.
Simple Null Object Pattern
class NullObject
# You can instantiate a new NullObject with arbitrary methods by calling
# NullObject.new({method1: "outcome1"})
# That will apply the method to the object
def initialize(methods={})
methods.each_pair do |k,v|
define_singleton_method k do |*params|
v
end
end
end
end
@Neener54
Copy link
Author

Say you need something that quacks like current_user.has_a_pony.
You can just do:

  def current_user
    User.find(id) || NullObject.new(:has_a_pony, true)
  end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment