koan_05_1.rb 582 B

123456789101112131415161718192021222324252627282930
  1. module Attributable
  2. def attribute(params='a')
  3. name = nil
  4. default_value = nil
  5. if params.is_a?(Hash)
  6. name = params.keys[0]
  7. default_value = params[name]
  8. else
  9. name = params
  10. end
  11. var_name = "@#{name}"
  12. define_method name do
  13. instance_variable_get(var_name) || default_value
  14. end
  15. define_method name + "?" do
  16. !send(name).nil?
  17. end
  18. define_method name + "=" do |value|
  19. instance_variable_set var_name, value
  20. end
  21. end
  22. end
  23. class SomeClass
  24. extend Attributable
  25. class << self
  26. extend Attributable
  27. end
  28. end