简体   繁体   English

方法级别的Rails API版本控制

[英]Rails API Versioning at Method Level

In .NET we were able to version our APIs at the method level by annotation them and only duplicating the methods that were different between versions. 在.NET中,我们能够通过对它们进行注释来在方法级别对API进行版本化,并且只复制版本之间不同的方法。 I've switched to a product team using Rails and am trying to figure out if there anything to help me do this in Rails. 我已经转而使用Rails的产品团队,并试图弄清楚是否有任何东西可以帮助我在Rails中做到这一点。 Everything I've seen so far suggests to namespace your entire controller(s) in a module with V1, V2, etc... when let's say only 1 method is different between V1 and V2, providing the potential to greatly reduce the amount of duplication necessary. 到目前为止我所看到的一切建议将整个控制器命名为V1,V2等模块...当假设V1和V2之间只有1种方法不同时,可以大大减少V1和V2的数量。必要的重复。

Thanks. 谢谢。

Ruby is an extremely flexible and rich language and it should not be hard to avoid code duplication. Ruby是一种非常灵活和丰富的语言,应该不难避免代码重复。

One, dirty and simple, way to manage your problem is by routing to appropriate actions. 管理问题的一种简单方法是路由到适当的操作。 In .NET you actually route requests by annotating method and not using any special language features. 在.NET中,您实际上通过注释方法路由请求,而不使用任何特殊语言功能。

# API::V2 implements only special_method
get '/api/v2/special_method', controller: 'API::V2', action: 'special_method' 

# all other actions from V2 are processed by V1
mount API::V1 => '/api/v1'
mount API::V1 => '/api/v2'

Another, more advanced, way is to use modules for implementing controller actions (instance methods). 另一种更高级的方法是使用模块来实现控制器动作(实例方法)。 Then you can reuse the same module in V2 of your API and override those method, which require to be changed. 然后,您可以在API的V2中重用相同的模块,并覆盖那些需要更改的方法。

class API::V1
  # implementaton of API::V1
  include ImplV1
end

class API::V2
  # all the methods from V1 are available in V2 too
  include ImplV1

  # override methods from V1 here
  include ImplV2
end

Lastly, a much more straightforward, but less flexible, way is to directly inherit V2 from V1: 最后,一种更简单但不太灵活的方法是直接从V1继承V2:

class API::V2 < API::V1
  def special_method
    # ...
  end
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM