Created
October 13, 2011 14:17
-
-
Save timruffles/1284322 to your computer and use it in GitHub Desktop.
NullObject
This file contains hidden or 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 initialize target_class | |
| @target_class = target_class | |
| end | |
| def method_missing method, *args, &block | |
| if @target_class.instance_methods.include?(method) | |
| nil | |
| else | |
| raise "Tried to call '#{method}' on a NullObject for #{@target_class}; method doesn't exist on #{@target_class}" | |
| end | |
| end | |
| end | |
| module HasNullObject | |
| def null_object | |
| @@null_object | |
| end | |
| def define_null_object &block | |
| @@null_object = NullObject.new(self) | |
| eigen = class << @@null_object; self; end | |
| eigen.class_eval &block | |
| end | |
| end | |
| class Partner | |
| def domain | |
| "http://c2.com/cgi/wiki" | |
| end | |
| def payment_method | |
| end | |
| # here we override our methods that should behave differently from returning nil | |
| extend HasNullObject | |
| define_null_object do | |
| def domain | |
| "http://land_of_the_nulls.com" | |
| end | |
| end | |
| end | |
| missing_partner = Partner.null_object | |
| puts missing_partner.payment_method | |
| puts missing_partner.domain | |
| puts missing_partner.domin |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment