koan_05_3.rb 709 B

1234567891011121314151617181920212223242526272829303132333435363738
  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. define_methods(name, default_value)
  12. end
  13. private
  14. def define_methods(name, default_value)
  15. var_name = "@#{name}"
  16. define_method name do
  17. instance_variable_get(var_name) || default_value
  18. end
  19. define_method name + "?" do
  20. !send(name).nil?
  21. end
  22. define_method name + "=" do |value|
  23. instance_variable_set var_name, value
  24. default_value = nil
  25. end
  26. end
  27. end
  28. class SomeClass
  29. extend Attributable
  30. class << self
  31. extend Attributable
  32. end
  33. end