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-agent
to all request done by open_uri
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)