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

3 tests, 7 assertions, 0 failures, 0 errors, 0 skips

Test run options: --seed 56210