如何从 ruby​​ on rails 中删除 https 和 http [英] How can I remove https and http from ruby on rails

查看:33
本文介绍了如何从 ruby​​ on rails 中删除 https 和 http的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从表单的 url 中删除https"和http",以便稍后显示图像,我得到了包含标题和 url 的表单,如下所示:

表格:

<%= form_for( @article, :html => { class: "form-test", role: "form"}) do |f|%><%= f.label:标题%><%= f.text_field :title%><%= f.label :Imagen%><%= f.text_field :img%><%= f.submit "Post"%><%结束%>

查看:

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

我正在寻找如何删除 https 的选项,如果您能告诉我,我将不胜感激.

解决方案

最佳实践是使用 ruby​​ URI,只要您的字符串只包含有效的 url.请参阅@CAmador 的答案,该答案由此演变而来.这两种解决方案都可以包装在帮助器中并在视图中使用.

def url_no_scheme(url)url = "https://foobar.com"uri = 网址(网址)uri.hostname + uri.path结尾url_no_scheme('https://foobar.com')=>foobar.com"url_no_scheme('http://foobar.com')=>foobar.com"

在视图中可以调用helper

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

这对于希望在 Rails 之外执行此操作的人可能会有所帮助,并且可能有一个包含多个 URL 的字符串,可以使用正则表达式将其删除:

str = "https://foobar.com 或 http://foobar.com"str.gsub(/https:\/\/|http:\/\//, "")=>foobar.com 或 foobar.com"

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.

解决方案

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"

这篇关于如何从 ruby​​ on rails 中删除 https 和 http的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆