fork download
  1. class ApiEndpoint
  2. attr_reader :fields
  3.  
  4. module FieldDispatcher
  5. def method_missing(method, *args)
  6. setter = method.to_s.end_with?('=')
  7.  
  8. if setter
  9. field = method[0..-2]
  10. else
  11. field = method
  12. end
  13.  
  14. expanded_path = "#{@root}#{field}"
  15.  
  16. if fields.has_key? expanded_path
  17. if setter
  18. fields[expanded_path] = args.first
  19. else
  20. fields[expanded_path]
  21. end
  22. elsif fields.keys.any? { |key| key.start_with? "#{expanded_path}." }
  23. ApiIntermediate.new(endpoint, "#{expanded_path}.")
  24. else
  25. super
  26. end
  27. end
  28. end
  29.  
  30. class ApiIntermediate
  31. attr_reader :endpoint
  32.  
  33. def initialize(endpoint, root)
  34. @endpoint, @root = endpoint, root
  35. end
  36.  
  37. def fields
  38. @endpoint.fields
  39. end
  40.  
  41. include FieldDispatcher
  42. end
  43.  
  44. def initialize(fields={})
  45. @fields = fields
  46. @root = ""
  47. end
  48.  
  49. include FieldDispatcher
  50.  
  51. protected
  52.  
  53. def endpoint
  54. self
  55. end
  56. end
  57.  
  58. require 'minitest/autorun'
  59.  
  60. class TestApiEndpoint < MiniTest::Unit::TestCase
  61. def setup
  62. @api = ApiEndpoint.new({
  63. 'foo' => 'bar',
  64. 'jp.hoge' => 'fuga',
  65. 'jp.piyo' => 'piyo',
  66. 'jp.legacy.ruby' => '1.6.5'
  67. })
  68. end
  69.  
  70. def test_plain
  71. assert_equal 'bar', @api.foo
  72. assert_raises NoMethodError do
  73. @api.foobar
  74. end
  75. end
  76.  
  77. def test_nested
  78. assert_equal 'fuga', @api.jp.hoge
  79. assert_equal 'piyo', @api.jp.piyo
  80. assert_raises NoMethodError do
  81. @api.jp.foobar
  82. end
  83. end
  84.  
  85. def test_deeply_nested
  86. assert_equal '1.6.5', @api.jp.legacy.ruby
  87. assert_raises NoMethodError do
  88. @api.jp.legacy.foobar
  89. end
  90. end
  91.  
  92. def test_set
  93. assert_raises NoMethodError do
  94. @api.quick = true
  95. end
  96.  
  97. @api.foo = "baz"
  98. assert_equal "baz", @api.fields['foo']
  99.  
  100. @api.jp.hoge = 'not actually'
  101. assert_equal 'not actually', @api.fields['jp.hoge']
  102. end
  103. end
Success #stdin #stdout 0.02s 5504KB
stdin
Standard input is empty
stdout
Loaded suite prog
Started
....
Finished in 0.001065 seconds.

4 tests, 10 assertions, 0 failures, 0 errors, 0 skips

Test run options: --seed 47898