Skip to content

Instantly share code, notes, and snippets.

@luigi
Created August 19, 2009 14:36
Show Gist options
  • Save luigi/170377 to your computer and use it in GitHub Desktop.
Save luigi/170377 to your computer and use it in GitHub Desktop.
require 'ostruct'
require 'pp'
class NewStruct < OpenStruct
def self.new(hash)
if hash.nil? || hash.empty?
return nil
else
super(hash)
end
end
end
class InitStruct < OpenStruct
def initialize(hash)
if hash.nil? || hash.empty?
return nil
else
super(hash)
end
end
end
puts "Instantiating OpenStruct..."
empty_struct = OpenStruct.new({})
pp empty_struct # returns an empty OpenStruct object
puts "Instantiating NewStruct..."
new_empty_struct = NewStruct.new({})
pp new_empty_struct # returns nil, the desired behavior
puts "Instantiating InitStruct..."
init_empty_struct = InitStruct.new({})
pp init_empty_struct # throws an exception
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment