Skip to content

Instantly share code, notes, and snippets.

@HaiTo
Last active April 5, 2018 04:29
Show Gist options
  • Save HaiTo/4d4c11116edd277d2ffe to your computer and use it in GitHub Desktop.
Save HaiTo/4d4c11116edd277d2ffe to your computer and use it in GitHub Desktop.
FaradayのリクエストのHashの特定のキーだけを抜き取ってLoggingするぞい。
require 'faraday'
require 'faraday_middleware'
require 'logger'
require 'pry-byebug'
module Faraday
class PivotLogging < Faraday::Middleware
# @param options [Hash] {logger: Rails::Logger.new, call_logging: 'info', pivot: pivot}
def initialize(app, options ={})
super(app)
@logger = options[:logger]
@call_logging = options[:call_logging]
@pivot = options[:pivot]
# optional
@message = options[:message] || ''
end
def call(env)
return env if lost_equipment?
@logger.send(@call_logging, message: @message, pivot: @pivot)
env
end
private
def lost_equipment?
@logger.nil? && @call_logging.nil? && @pivot.nil?
end
def post_or_put?(env)
%i(post put).include?(env[:method])
end
def parse_body(env)
# NOTE JSON としてパースしてみて、ダメだったらURLEncodeとして再パース。それでもダメだったら諦める。
begin
JSON.load(env.body)
rescue JSON::ParserError
# 'id=1&hoge=2'.split('&').each_with_object({}){|str, hs| key, value = str.split('='); hs[key.to_sym] = value }
# #=> {:id=>"1", :hoge=>"2"} だいたいこんな感じ。
parse_url_encoded_params(env.body)
rescue
{}
end
end
def parse_url_encoded_params(string)
string.split('&').each_with_object({}) {|str, hs| key, value = str.split('='); hs[key.to_sym] = value }
end
end
end
logger = Logger.new('log.log.log')
conn = Faraday.new(url: 'http://localhost:4567') do |builder|
builder.use Faraday::Request::UrlEncoded
#builder.use FaradayMiddleware::EncodeJson
builder.use Faraday::PivotLogging, {logger: logger, call_logging: 'info', pivot: 'id'}
builder.use Faraday::Adapter::NetHttp
end
conn.post('/hoge.json', {id: '1', hoge: '2'})
@HaiTo
Copy link
Author

HaiTo commented Jul 22, 2015

それでもダメだったら、というのは実際ありえなくて、むりくりパースしちゃう。

@HaiTo
Copy link
Author

HaiTo commented Jul 22, 2015

'hoge:'.split('&').each_with_object({}){|str, hs| key, value = str.split('='); hs[key.to_sym] = value }
=> {:"hoge:"=>nil}

'id=1_hoge=2'.split('&').each_with_object({}){|str, hs| key, value = str.split('='); hs[key.to_sym] = value }
=> {:id=>"1_hoge"}

実際、文字列以外が来たらアウトなだけで。それはFaradayの構造上ありえないから、最後の rescue は実はいらない。

@HaiTo
Copy link
Author

HaiTo commented Jul 22, 2015

実は env を返すのは必要なさそう?

@HaiTo
Copy link
Author

HaiTo commented Jul 22, 2015

まぁLoggingするだけだから、ちゃんと返しましょうという意図を込めて。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment