Rails5 で Faraday を使ってみる
Ruby Ruby on Rails
Published: 2019-06-07

やったこと

Rails5 で Faraday を使ってみます。

確認環境

$ ruby --version
ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-darwin17]

$ rails --version
Rails 5.2.3

調査

インストール

Gemfile

gem 'faraday'
$ bundle install

使ってみる

app/controllers/tasks_controller.rb

class TasksController < ApplicationController

  def index
    render :json => {c:3, d:4}
  end

  def new
    uri = 'http://127.0.0.1:3000/'
    conn = Faraday::Connection.new(:url => uri) do |builder|
      builder.use Faraday::Adapter::NetHttp
      builder.use Faraday::Response::Logger
    end
    res = conn.get "/", {a:1, b:2}
    logger.debug(res.body)
  end
end

URL にアクセス

$ curl http://localhost:3000/tasks/new
$ less log/development.log
Started GET "/tasks/new" for ::1 at 2019-06-07 00:37:53 +0900
Processing by TasksController#new as */*
Started GET "/?a=1&b=2" for 127.0.0.1 at 2019-06-07 00:37:53 +0900
Processing by TasksController#index as */*
  Parameters: {"a"=>"1", "b"=>"2"}
Completed 200 OK in 1ms (Views: 0.3ms | ActiveRecord: 0.0ms)


{"c":3,"d":4}
  Rendering tasks/new.html.erb within layouts/tasks
  Rendered tasks/new.html.erb within layouts/tasks (0.3ms)
Completed 200 OK in 45ms (Views: 33.4ms | ActiveRecord: 0.0ms)

参考