Skip to content

Instantly share code, notes, and snippets.

@chad
Created April 1, 2012 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chad/2275456 to your computer and use it in GitHub Desktop.
Save chad/2275456 to your computer and use it in GitHub Desktop.
class Class
def attr_with_default(attr_name, default_value)
attr_writer attr_name
define_method(attr_name) do
instance_variable_get("@#{attr_name}") || default_value
end
end
end
class Person
attr_with_default :age, 3
end
person = Person.new
p person.age # => 3
person.age = 30
p person.age # => 30
class Class
def defaults(hash)
hash.each do |attribute_name, default_value|
define_method(attribute_name) do
instance_variable_get("@#{attribute_name}") || instance_variable_set("@#{attribute_name}", default_value)
end
end
end
end
class Video
attr_accessor :width, :height
defaults :width => 400, :height => 300
end
v = Video.new
p v.width
p v.height
v.width = 123
p v.width
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment