5

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.

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much this is awesome.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.