Skip to content

Instantly share code, notes, and snippets.

@stephenaument
Created March 8, 2014 07:22
Show Gist options
  • Save stephenaument/9426713 to your computer and use it in GitHub Desktop.
Save stephenaument/9426713 to your computer and use it in GitHub Desktop.
The Null Object Pattern
class CreateDucks < ActiveRecord::Migration
def change
t.string name
t.string status
t.integer hunger
t.string quack_style
t.string color
t.migratory boolean
end
end
class CreateDucks < ActiveRecord::Migration
def change
t.string name
t.string status
t.integer hunger
t.string quack_style
t.string color
t.string secondary_color
t.migratory boolean
end
end
class Duck < ActiveRecord::Base
def awake?
status == 'awake'
end
def quack
puts quack_style
end
end
class Duck < ActiveRecord::Base
def awake?
status == 'awake'
end
def quack
puts quack_style
end
def multi_colored?
!secondary_color.nil?
end
end
//javascript
{ multiColored: #{duck.multi_colored?} }
// javascript
{ multiColored: } // !!! Not a valid JSON object, buddy!
// javascript
{ multiColored: false }
class NilDuck
attr_writer :name, :status, :hunger, :quack_style, :color, :migratory
def name
'Demo Duck'
end
def status
'sleeping'
end
def hunger
nil
end
def quack
end
def quack_style
nil
end
def color
'gray'
end
def awake?
false
end
def migratory
nil
end
def migratory?
true
end
end
class NilDuck
def name
'Demo Duck'
end
def status
'sleeping'
end
def color
'gray'
end
def migratory?
true
end
def method_missing(name, *args)
Duck.new.respond_to?(name) ? nil : super
end
end
class NilDuck
def name
'Demo Duck'
end
def status
'sleeping'
end
def color
'gray'
end
def migratory?
true
end
def method_missing(name, *args)
super unless Duck.new.respond_to?(name)
name.ends_with?('?') ? false : nil
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment