处理来自 HTTP 请求的用户输入通常在控制器中完成。
向 Rails 服务器发送一个请求,包括用户输入。
请求将被路由到适当的控制器操作。在控制器操作中,向外部 API 发送 HTTP 请求,并使用 RestClient 之类的东西将用户输入包含在请求中。
最后,您将向用户发送一封电子邮件,并通过调用交付来包含请求状态!邮件类的方法。
例子:
class UsersController < ApplicationController
def controller_action
@user_input = params[:query]
# Build the external API request URI.
# Using www.icd10api.com as an example.
url = Addressable::URI.new(
scheme: "http",
host: "www.icd10api.com",
query_values: {code: @user_input, r: "json", desc: "long"})
# Perform the external request and parse the response
resp = JSON.parse(RestClient.get(url.to_s))
# Finally, deliver the email.
UserMailer.statuses_email(resp).deliver!
# Return status code
render status: 200
end
end
您始终可以将您的代码重构为一个模块,但我只在它用于 3 个以上的位置时才这样做。
如果您不只是将其用作演示应用程序,我会参考 Andrew CP Kelley 评论中的链接:
Where do API calls go in a ruby on rails MVC framework project?
参考资料:
https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
如果您使用的是 rails 4+,您可能还想调查一下问题:
How to use concerns in Rails 4