2013-07-31 10 views

回答

0

由於http://包含這麼多for ward斜槓,這對於Ruby的%r正則表達式語法來說非常有用。

def has_forbidden_prefix?(string) 
    string =~ %r{^(http://|www)} 
end 

這將返回nil,falsy,如果字符串不http://www啓動。

如果字符串的話,它將返回0,truthy(第一個匹配的偏移量)。

您可以使用validate :some_method_name調用自定義的驗證方法的模型,我可以按如下方式構建它

model MyThing 
    validate :no_forbidden_prefix 

    private 

    def has_forbidden_prefix?(string) 
    string =~ %r{^(http://|www)} 
    end 

    def no_forbidden_prefix 
    if has_forbidden_prefix?(uri) 
     errors.add :domain, 'The URI cannot start with "http://" or "www"' 
    end 
    end 
end 
+0

謝謝,我編輯了我的問題。我如何在您的模型中包含您的解決方案? – crispychicken

+0

我已經擴展了我的解決方案以提供示例實現,我發現使用私有方法的自定義驗證更具可讀性,但這僅僅是我的看法。 :) –

+0

未定義的本地變量或方法'uri' – crispychicken

0

這應該爲你做它:

/^[http\:\/\/|www].*/ 

例如:

1.9.2p320 :007 > "http://www.google.de".match /^[http\:\/\/|www].*/ 
=> #<MatchData "http://www.google.de"> 
1.9.2p320 :008 > "www.google.de".match /^[http\:\/\/|www].*/ 
=> #<MatchData "www.google.de"> 
1.9.2p320 :009 > "google.de".match /^[http\:\/\/|www].*/ 
=> nil 

因此,如果有效doenst比賽爲您的目的...

+0

'[HTTP \:\/\/| WWW]'是一個字符類,也許你打算使用分組? – toro2k

+0

謝謝,但是當我做類似這樣的事情時,它不起作用:「www.google.com」.sub(/^[http \:\/\/| www] ./,「」)=>「w。 google.com「 – crispychicken

+0

@ toro2k是的,我需要使用分組 – crispychicken