koan_06_0.rb 892 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. end
  31. end
  32. end
  33. class SomeClass
  34. extend Attributable
  35. class << self
  36. extend Attributable
  37. end
  38. end