koan_08_0.rb 862 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. attribute_value = nil
  20. define_method name do
  21. default_value = instance_eval &block unless block.nil?
  22. attribute_value || default_value
  23. end
  24. define_method name + "?" do
  25. !send(name).nil?
  26. end
  27. define_method name + "=" do |value|
  28. attribute_value = value
  29. default_value = nil
  30. block = nil
  31. end
  32. end
  33. end
  34. class SomeClass
  35. end
  36. class Module
  37. include Attributable
  38. end