【问题标题】:How can I remove https and http from ruby on rails如何从 ruby​​ on rails 中删除 https 和 http
【发布时间】:2022-01-29 02:20:30
【问题描述】:

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

表格:

<%= 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 %>

查看:

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

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

【问题讨论】:

  • 你的意思是,你想在你的应用中禁用 https 吗?
  • 为什么不使用Let's Encrypt 并将您的站点升级到HTTPS,而不是假设其他站点将在HTTP 模式下工作,这可能不是由于HSTS。例如,整个.app gTLD 需要 HTTPS,它不是可选的。
  • 我只想从img中删除http和https
  • 您是要在数据库中删除它们还是仅在视图中删除它们?

标签: ruby-on-rails ruby


【解决方案1】:

Ruby 的URI 可能吗?

~ ᐅ 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" 

您可以为此定义一个助手:

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

查看:

<div class="header">
  <%= image_tag(url_without_scheme @article.img) %>
  <%= @article.title%>
</div>

【讨论】:

  • 你是对的,建议一个帮手,我会支持你的答案。
  • 如果你停止制作一个不必要的数组,而只自己对这两个部分进行字符串插值,那么基准是什么样的?数组很慢。
  • 更新答案删除不必要的数组。泰,@Nate ;-)
  • 用更新方法进行基准测试,结果相同。但是如果源已经删除了 http 呢?然后它会在正则表达式不会的地方提出。
  • 当您没有连续执行 10000 次时,谁在乎正则表达式是否更快?如果您没有方案,URI 也不会提高。 URI('my.domain.com/my_image.png') 只是给你一个URI::Generic
【解决方案2】:

最好的做法是使用 ruby​​ URI,只要你的字符串只包含一个有效的 url。请参阅@CAmador 的答案,该答案是从该答案演变而来的。任何一种解决方案都可以包装在帮助程序中并在视图中使用。

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"

在视图中你可以调用助手

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

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

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

【讨论】:

  • 我认为URL在这个解决方案中应该是URIuri = URI(url)
  • @ShawnAukstak 谢谢,已更新。
猜你喜欢
  • 1970-01-01
  • 2013-10-21
  • 1970-01-01
  • 2014-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多