koan_09_1.rb 848 B

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. class SomeClass
  2. end
  3. class Module
  4. def attribute(params='a', &block)
  5. name, default = process_args(params)
  6. ivar = "@#{name}"
  7. assigned = ivar + "_assigned"
  8. # getters
  9. define_method name do
  10. default = instance_eval &block if block # set default to block
  11. attr_set = !instance_variable_get(assigned).nil?
  12. instance_variable_get(ivar) || (default unless attr_set)
  13. end
  14. # predicates
  15. define_method(name + "?") { !send(name).nil? }
  16. # setters
  17. define_method name + "=" do |value|
  18. instance_variable_set ivar, value
  19. instance_variable_set assigned, true
  20. end
  21. end
  22. private
  23. def process_args(params)
  24. name = nil
  25. default = nil
  26. if params.is_a?(Hash)
  27. name = params.keys[0]
  28. default = params[name]
  29. else
  30. name = params
  31. end
  32. [name, default]
  33. end
  34. end