Created
January 11, 2012 22:26
-
-
Save coffeencoke/1597151 to your computer and use it in GitHub Desktop.
How to? default hash paramater being given as nil
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 Something | |
def initialize(hash={}) | |
hash ||= {} # Do not want to do this! | |
@my_attribute = hash[:my_attribute] | |
end | |
end | |
Something.new(nil) # nil param happens with forms occasionally | |
Something.new({}) | |
Something.new(:my_attribute => 'something') |
make Hash
, an analog of the handy Array
module Kernel
def Hash(possible_hash); possible_hash || {}; end
end
class Something
def initialize(hash={})
@my_attribute = Hash(hash)[:my_attribute]
end
end
Something.new(nil) # nil param happens with forms occasionally
Something.new({})
Something.new(:my_attribute => 'something')
Or use OpenStruct
class Something
def initialize(hash={})
@my_attribute = OpenStruct.new(hash).my_attribute
end
end
Something.new(nil) # nil param happens with forms occasionally
Something.new({})
Something.new(:my_attribute => 'something')
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How to eliminate line 3?