Rewrite User-Agent to all Open URI Request

Viewed 544

Using Rails 4.2.10

I would like to open image from URL thanks to mongoid papaerclip and open_uri

It perfectly works in 95% of use cases but some website send me a 404 when they see the user-agent of the request is Ruby.

The problem is with the lib paperclip=> paperclip/io_adapters/uri_adapter.rb in download_content at line 48

def download_content
    options = { read_timeout: Paperclip.options[:read_timeout] }.compact

    open(@target, **options)
end

If I could add here an option it would be great but I don't think it's possible so I would like to add a default header with my user-agentto all request done by open_uri

2 Answers

Luckily for your use case there is no such thing as a class being closed against modification in ruby.

Add a patch to your rails app in an initializer. The structure is roughly as follows:

In config/initializers/some_arbitrary_name.rb

module UriAdapterPatch
  def open(url, options)
    # alter the objects however you want
    super(altered_or_original_url, altered_or_original_options)
  end
end

Paperclip::UriAdapter.prepend(UriAdapterPatch)

Solution for paperclip-3.5.4

module Paperclip
  class UriAdapter < AbstractAdapter
    def download_content
      open(@target,"User-Agent" => "Your Custom User Agent")
    end
  end
end

# for example put it in config/initializers/paperclip_user_agent.rb

For other versions just write in project folder

gem which paperclip

and find in path from output file paperclip/io_adapters/uri_adapter.rb

There is function def download_content, it is your aim to rewrite

Related