Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails URL generator switch http / https

Is there a way to put in links to external resources that automatically adds the protocol based on the current protocol?

For example I want to show images from Facebook's Graph API. I was hoping I could do something like:

image_tag url_for("/1234567/picture", :host => "graph.facebook.com")

So that the url_for just bases the protocol on the current request's protocol.

I know this works but I'm hoping there's a better way:

image_tag("#{request.protocol}://graph.facebook.com/1234567/picture")
like image 513
Heinrich Lee Yu Avatar asked Jan 24 '26 12:01

Heinrich Lee Yu


1 Answers

You can add the protocol option to url_for.

image_tag url_for("/1234567/picture", :host => 'graph.facebook.com', :protocol => request.protocol)

or maybe a better way would be to create a helper (if you do this a lot) called url_for_same_protocol (or whatever you want):

class ApplicationHelper
  def url_for_same_protocol(url, options)
    options[:protocol] ||= request.protocol
    url_for url, options
  end
end

.. and then just replace your url_for call with url_for_same_protocol.

like image 198
AndrewF Avatar answered Jan 26 '26 01:01

AndrewF



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!