Skip to content

Instantly share code, notes, and snippets.

@banister
Created March 1, 2012 03:26
Show Gist options
  • Save banister/5cf27742477cd4c75dcd to your computer and use it in GitHub Desktop.
Save banister/5cf27742477cd4c75dcd to your computer and use it in GitHub Desktop.
class Bing
def self.attr_with_defaults(hash={})
hash.each do |name, value|
attr_writer name
define_method(name) do
instance_variable_defined?("@#{name}") ? instance_variable_get("@#{name}") : value
end
end
end
end
# => nil
class Bing
attr_with_defaults :john => "cutie"
end
# => {:john=>"cutie"}
b = Bing.new
# => #<Bing:0x00000102825980 @john="carl">
b.john
# => "cutie"
b.john = "carl"
# => "carl"
b.john
# => "carl"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment