How can I remove https and http from ruby on rails

旧城冷巷雨未停 提交于 2021-02-19 06:49:04

问题


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.


回答1:


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 = URL(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"



回答2:


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>


来源:https://stackoverflow.com/questions/55854766/how-can-i-remove-https-and-http-from-ruby-on-rails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!