1

My task is to take some data from users. The next part is to make permanent requests to an API of a third party site and to process responses from it. I don't know where this part should be placed: model, controller, or module? The final part of the app will send statuses to users' emails.

sawa
  • 165,429
  • 45
  • 277
  • 381
nobilik
  • 736
  • 9
  • 29
  • In my view, it will be in controller - given that you say its a small project. – Wand Maker Nov 18 '15 at 18:45
  • Depends, but I would argue that third party API request should be encapsulated in an module or at least in a model. – spickermann Nov 18 '15 at 18:49
  • As per my view, it should be extract out into service that will interact with 3party service, and as soon as the service will get the response from the 3rd party, it will notify the model, and then model will take appropriate action. – Kuldeep Nov 18 '15 at 19:04

2 Answers2

1

Processing user input from an HTTP request is usually done in the controller.

Send a request to the rails server including the user input.

The request will be routed to the appropriate controller action. In the controller action, form an HTTP request to an external API and include the user input in the request using something like RestClient.

Finally, you will send an email to the user and include the request statuses by calling the deliver! method on a mailer class.

Example:

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

You can always refactor your code into a module, but I only do this if it's used in 3+ locations.

If you're using this as more than a demo app, I would refer to the link in Andrew CP Kelley's comment:

Where do API calls go in a ruby on rails MVC framework project?

References:

https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller

You also might want to look into concerns if you're using rails 4+:

How to use concerns in Rails 4

Community
  • 1
  • 1
teixeir3
  • 86
  • 6
0

I usually wrap it inside a module or a class and place the file into folder

app/models/services/

Here is the folder I place all things are kind of service, e.g. The logic to requests to API and proceed responses from it.

Long Nguyen
  • 11,075
  • 2
  • 18
  • 25