koan_09_1o.rb 935 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. class SomeClass
  2. end
  3. # NOTE: This is the original koan_09_1.rb but has a regression failure.
  4. # The current koan_09_1.rb, and koan_09_2.rb show another way to inline
  5. # method definitions.
  6. class Module
  7. def attribute(params='a', &block)
  8. name, default_value = process_args(params)
  9. value = default_value
  10. attribute_assigned = false
  11. define_method(name) do
  12. unless value
  13. if attribute_assigned or block.nil?
  14. nil
  15. else
  16. instance_eval &block
  17. end
  18. else
  19. value
  20. end
  21. end
  22. define_method(name + "?") { !send(name).nil? }
  23. define_method(name + "=") { |new_value| value = new_value; attribute_assigned = true }
  24. end
  25. private
  26. def process_args(params)
  27. name = nil
  28. default_value = nil
  29. if params.is_a?(Hash)
  30. name = params.keys[0]
  31. default_value = params[name]
  32. else
  33. name = params
  34. end
  35. [name, default_value]
  36. end
  37. end