Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove https and http from ruby on rails

I need to remove the "https" and the "http" from a url from my form in order to show the image later, I got the form where i'm including title and url like this:

Form:

<%= form_for( @article, :html => { class: "form-test", role: "form"}) do |f| %>      
    <%= f.label :Titulo %>
    <%= f.text_field :title%>

    <%= f.label :Imagen%>
    <%= f.text_field :img%>

     <%= f.submit "Post"%>
<% end %>

View:

<div class="header">
    <%= image_tag("https://#{@article.img}") %>
    <%= @article.title%>
</div>

I'am looking for option how should I remove the https I will really appreciate if you can tell me.

like image 585
JULIO MACHAN Avatar asked Jul 12 '26 06:07

JULIO MACHAN


2 Answers

Ruby's URI maybe?

~ ᐅ irb                                                                                                                                                                                                                         [ruby-2.5.3] 
2.5.3 :001 > uri = URI('https://my.domain.com/my_image.png')
 => #<URI::HTTPS https://my.domain.com/my_image.png> 
2.5.3 :002 > [uri.hostname, uri.path].join
 => "my.domain.com/my_image.png" 

You can define a helper for that:

def url_without_scheme(url)
  uri = URI(url)
  uri.hostname + uri.path
end

View:

<div class="header">
  <%= image_tag(url_without_scheme @article.img) %>
  <%= @article.title%>
</div>
like image 143
CAmador Avatar answered Jul 14 '26 20:07

CAmador


Best practice is to use ruby URI so long as your string only contains a valid url. See answer by @CAmador from which this answer evolved. Either solution can be wrapped in a helper and used in the view.

def url_no_scheme(url)
  url = "https://foobar.com"
  uri = URI(url)
  uri.hostname + uri.path
end

url_no_scheme('https://foobar.com')
=>"foobar.com"    
url_no_scheme('http://foobar.com')
=>"foobar.com"

In the view you can call the helper

<%= image_tag(url_without_scheme @article.img) %> 

This might be helpful for someone looking to do this outside of rails and may have a string with multiple URLs which can be removed with a regular expression:

str = "https://foobar.com or http://foobar.com"
str.gsub(/https:\/\/|http:\/\//, "")
=> "foobar.com or foobar.com"
like image 37
lacostenycoder Avatar answered Jul 14 '26 18:07

lacostenycoder