livingsocial / swagger_yard

Swagger-UI compliant JSON generated from YARD. For RESTful Rails apps.
MIT License
51 stars 28 forks source link

Fix - Clear Yard Registry to use swagger_yard with Sinatra splited routes files #68

Open AntoineGirard opened 3 years ago

AntoineGirard commented 3 years ago

Allow to use it, with Sinatra routes splited in multiple files.

Sinatra doesn't have the concept of controller like Rails. If you want to split your routes in multiple files you need to do something like this.

Before split

MyApp < Sinatra::Application
  get "/user/{id}" do
    …
  end

  post "/user" do
    …
  end

  get "/article/{id}" do
    …
  end

  …
end

After split

user.rb

# @resource User
MyApp < Sinatra::Application
  # Returns user
  #
  # @path [GET] /user/{id}
  get "/user{id}" do
    …
  end

  # Save and returns user
  #
  # @path [POST] /user
  post "/user" do
    …
  end
end

article.rb

# @resource Article
MyApp < Sinatra::Application
  # Returns article
  #
  # @path [GET] /article/{id}
  get "/article/{id}" do
    …
  end

  # Save and returns article
  #
  # @path [POST] /article
  post "/article" do
    …
  end
end

In this case, only the first file documentation is returned by Swagger#to_h if your config.controller_path is set to routes/**/* because Yard save methods of all files in class MyApp associated to the first file analyzed path.

Example:

Specification#parse_controllers analyzed my previous file in this order : user -> article.

By clearing Yard Registry each time, this permit to return methods for each file and tags associated to these methods.

It shouldn't have side effects cause Yard::Registry is only use here.

I hope that my explanations are clear enough. If you have any comments or questions, please let me know.

nicksieger commented 3 years ago

Hey Antoine, thanks for this contribution! The only issue I'll point out is that back in v0.3.1 the caching functionality of the registry is specifically called out, and is useful in my opinion for larger codebases when using, for example, the swagger controller in swagger_yard-rails. I wonder if we could either make this clearing behavior configurable or find another way to solve your issue. I'll try to think of other ways of solving this too. It might help to have a test case to demonstrate the behavior also. Let me know if you want to try that and need any help with it.

AntoineGirard commented 3 years ago

Hey @nicksieger Thanks for your answer. I didn't see this side effect. For now, I think the best solution is to make this cache usage configurable. I proposed an implementation. I think we could find another solution but I have no idea for now.