将用户输入的 url 转换为 rails 中的外部链接 [英] Make user-inputted url into external link in rails
问题描述
我希望用户能够输入一个 url,然后在我的视图中放置一个指向该 url 的链接.
有效输入可以是例如https://www.google.com/path
、http://www.google.com
、www.google.com
>
是否有标准的 Rails 方法来 1)验证输入是有效的 url 格式,2)在我的视图中将第三种格式转换为 http://www.google.com
以便外部链接有效吗?
如果可以避免的话,我不想重新发明轮子.
看看这个:
validates_format_of :website, :with =>URI::regexp(%w(http https))
来源:http://inridea.com/2009/2/18/quick-tip-url-validation-in-rails?blog=company
要格式化一个缺少协议(http 或 https)的 URL,我会做一个 before_save 钩子,如果它丢失了它:
before_save :format_url...定义格式_urlself.website = "http://#{self.website}" 除非 self.website[/^https?/]结尾
I want users to be able to enter a url and then put a link to that url in my view.
Valid inputs could be e.x. https://www.google.com/path
, http://www.google.com
, www.google.com
Is there are standard rails way to 1) validate that input is a valid url format and 2) convert that third format to http://www.google.com
in my views so the external link works?
I don't want to re-invent the wheel if I can avoid it.
Check this out:
validates_format_of :website, :with => URI::regexp(%w(http https))
Source: http://intridea.com/2009/2/18/quick-tip-url-validation-in-rails?blog=company
To format a URL that is missing the protocol (http or https), I would do a before_save hook that prepends it if it's missing:
before_save :format_url
...
def format_url
self.website = "http://#{self.website}" unless self.website[/^https?/]
end
这篇关于将用户输入的 url 转换为 rails 中的外部链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!