web_request_concern.rb 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. require 'faraday'
  2. require 'faraday_middleware'
  3. module WebRequestConcern
  4. extend ActiveSupport::Concern
  5. def validate_web_request_options!
  6. if options['user_agent'].present?
  7. errors.add(:base, "user_agent must be a string") unless options['user_agent'].is_a?(String)
  8. end
  9. unless headers(options['headers']).is_a?(Hash)
  10. errors.add(:base, "if provided, headers must be a hash")
  11. end
  12. begin
  13. basic_auth_credentials(options['basic_auth'])
  14. rescue ArgumentError => e
  15. errors.add(:base, e.message)
  16. end
  17. end
  18. def faraday
  19. @faraday ||= Faraday.new { |builder|
  20. builder.headers = headers if headers.length > 0
  21. builder.headers[:user_agent] = user_agent
  22. builder.use FaradayMiddleware::FollowRedirects
  23. builder.request :url_encoded
  24. if userinfo = basic_auth_credentials
  25. builder.request :basic_auth, *userinfo
  26. end
  27. case backend = faraday_backend
  28. when :typhoeus
  29. require 'typhoeus/adapters/faraday'
  30. end
  31. builder.adapter backend
  32. }
  33. end
  34. def headers(value = interpolated['headers'])
  35. value.presence || {}
  36. end
  37. def basic_auth_credentials(value = interpolated['basic_auth'])
  38. case value
  39. when nil, ''
  40. return nil
  41. when Array
  42. return value if value.size == 2
  43. when /:/
  44. return value.split(/:/, 2)
  45. end
  46. raise ArgumentError.new("bad value for basic_auth: #{value.inspect}")
  47. end
  48. def faraday_backend
  49. ENV.fetch('FARADAY_HTTP_BACKEND', 'typhoeus').to_sym
  50. end
  51. def user_agent
  52. interpolated['user_agent'].presence || self.class.default_user_agent
  53. end
  54. module ClassMethods
  55. def default_user_agent
  56. ENV.fetch('DEFAULT_HTTP_USER_AGENT', Faraday.new.headers[:user_agent])
  57. end
  58. end
  59. end