Rails API与原始Rails的区别

4
在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部分有一些不必要的功能,而我又不需要这些功能。那么我应该创建两个单独的控制器:
class ApplicationController < ActionController::Base
end

并且

class ApiController < ActionController::API
end
1个回答

0

使用面向对象编程(OOP)来建模你的应用程序

假设你的网站和API共享所有行为,那么你可以这样做:ApplicationController < ActionController::Base。扩展ApplicationController的API控制器将可以访问一些它们实际上不需要的东西...无论如何。

如果你的网站和API没有共享任何行为,那么你可以这样做:ApiController < ActionController::APIApplicationController < ActionController::Base

如果它们只共享一些行为,你可能想做的是:ApplicationController < ActionController::BaseApiController < ApplicationControllerWebsiteController < ApplicationController

话虽如此,有时仅仅使用单一类继承很难做到完美。这时候你可以使用concerns

希望我表达清楚了。


感谢您的建议。 - dungdm93

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接