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. 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. 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.
Thanks.
Ruby is an extremely flexible and rich language and it should not be hard to avoid code duplication.
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.
# 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.
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:
class API::V2 < API::V1
def special_method
# ...
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With