Rails API 和原来的 Rails
Rails API and original Rails
在 Rails 应用程序中,ApplicationController 如:
class ApplicationController < ActionController::Base
end
如果我们想创建一个仅 API 的应用程序,它不需要完整的 Rails 应用程序提供的所有功能:
class ApplicationController < ActionController::API
end
我的问题是,如果我希望我的 Rails 应用程序同时提供原始 Web 应用程序和 Web API,那么最佳做法是:
我的意思是,我只是使用:
class ApplicationController < ActionController::Base
end
如果那样,Rails::API 部分有一些不必要的功能,我不想要这个。
或者我应该创建 2 个分离的控制器:
class ApplicationController < ActionController::Base
end
和
class ApiController < ActionController::API
end
使用 OOP 为您的应用程序建模
假设您的网站和您的 api 共享所有行为,那么您会:ApplicationController < ActionController::Base
。扩展 ApplicationController
的 API 控制器将可以访问一些他们实际上并不需要的东西……无论如何。
如果您的网站和 api 不共享任何行为,那么您会:ApiController < ActionController::API
、ApplicationController < ActionController::Base
如果他们只分享某些行为,您可能想要做的是:
ApplicationController < ActionController::Base
、ApiController < ApplicationController
、WebsiteController < ApplicationController
也就是说,有时很难仅通过单一 class 继承就把所有事情都做好。然后你可以做的是使用 concerns .
希望我说清楚了
在 Rails 应用程序中,ApplicationController 如:
class ApplicationController < ActionController::Base
end
如果我们想创建一个仅 API 的应用程序,它不需要完整的 Rails 应用程序提供的所有功能:
class ApplicationController < ActionController::API
end
我的问题是,如果我希望我的 Rails 应用程序同时提供原始 Web 应用程序和 Web API,那么最佳做法是: 我的意思是,我只是使用:
class ApplicationController < ActionController::Base
end
如果那样,Rails::API 部分有一些不必要的功能,我不想要这个。 或者我应该创建 2 个分离的控制器:
class ApplicationController < ActionController::Base
end
和
class ApiController < ActionController::API
end
使用 OOP 为您的应用程序建模
假设您的网站和您的 api 共享所有行为,那么您会:ApplicationController < ActionController::Base
。扩展 ApplicationController
的 API 控制器将可以访问一些他们实际上并不需要的东西……无论如何。
如果您的网站和 api 不共享任何行为,那么您会:ApiController < ActionController::API
、ApplicationController < ActionController::Base
如果他们只分享某些行为,您可能想要做的是:
ApplicationController < ActionController::Base
、ApiController < ApplicationController
、WebsiteController < ApplicationController
也就是说,有时很难仅通过单一 class 继承就把所有事情都做好。然后你可以做的是使用 concerns .
希望我说清楚了