次のサンプル 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? %>