0

Case: A User's Profile where he can add a bunch of links.

I collect the links via the User Registration Page, but i'm having a Problem with Users not entering www. and http:// in front of the URL.

I could fix the http:// problem with auto_link but i have to many users just typing example.com.

How can i extract the URL from a String, even if it is without www. or http:// (The field contains ONLY the url).

Display Code:

<% if @user.website.present? %>
  <li>
    <%= link_to @user.website, target: '_blank' do %>
      <i class="fa fa-globe"></i> <span>Website</span>
    <% end %>
  </li>
<% end %>
4

1 に答える 1

1

次のサンプル URL を検討してください。

text1="example.com/foo/bar"
text2="www.example.com/foo/bar"
text3="http://www.example.com/foo/bar"
text4="https://www.example.com/foo/bar"

これ:

gsub(/\A(http(s)?:\/\/)?(www\.)?(.*)/,"http\\2://www.\\4")

以下を出力します。

text1.gsub(/\A(http(s)?:\/\/)?(www\.)?(.*)/,"http\\2://www.\\4") 
# http://www.example.com/foo/bar

text2.gsub(/\A(http(s)?:\/\/)?(www\.)?(.*)/,"http\\2://www.\\4") 
# http://www.example.com/foo/bar

text3.gsub(/\A(http(s)?:\/\/)?(www\.)?(.*)/,"http\\2://www.\\4") 
# http://www.example.com/foo/bar

text4.gsub(/\A(http(s)?:\/\/)?(www\.)?(.*)/,"http\\2://www.\\4") 
# https remains
# https://www.example.com/foo/bar 

したがって、link_to 外部リンクを使用する場合:

<%= link_to '<i class="fa fa-globe"></i> <span>Website</span>'.html_safe, 
    @user.website.
    gsub(/\A(http(s)?:\/\/)?(www\.)?(.*)/,"http\\2://www.\\4") unless
    @user.website.nil? %>

編集:

上記のケースには悪い例外があります。

text5="http://example.com/foo/bar"

上記の置換が返されます

http://www.example.com/foo/bar # inserting a "www"

ほとんどの場合、これは問題ありません。したがって、置換する条件を指定する必要があります。次のようなヘルパー メソッドを作成することをお勧めします。

def url_to_external(text)
    /\Ahttp(s)?:\/\//.match(text) ? text : text.gsub(/\A(http(s)?:\/\/)?(www\.)?(.*)/,"http\\2://www.\\4")
end

文字列の先頭に「http://」または「https://」がない場合にのみ置き換えられます。

あなたの見解では、次のようになります。

<%= link_to '<i class="fa fa-globe"></i> <span>Website</span>'.html_safe,
    url_to_external(@user.website) unless @user.website.nil? %>
于 2014-04-09T11:50:21.633 に答える