koan_06_1.rb 910 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. module Attributable
  2. def attribute(params='a', &block)
  3. name, default_value = process_args(params)
  4. define_methods(name, default_value, &block)
  5. end
  6. private
  7. def process_args(params)
  8. name = nil
  9. default_value = nil
  10. if params.is_a?(Hash)
  11. name = params.keys[0]
  12. default_value = params[name]
  13. else
  14. name = params
  15. end
  16. [name, default_value]
  17. end
  18. def define_methods(name, default_value, &block)
  19. var_name = "@#{name}"
  20. define_method name do
  21. default_value = block.call unless block.nil?
  22. instance_variable_get(var_name) || default_value
  23. end
  24. define_method name + "?" do
  25. !send(name).nil?
  26. end
  27. define_method name + "=" do |value|
  28. instance_variable_set var_name, value
  29. default_value = nil
  30. block = nil
  31. end
  32. end
  33. end
  34. class SomeClass
  35. extend Attributable
  36. class << self
  37. extend Attributable
  38. end
  39. end