2016-02-23 84 views
1

匹配字符串在Rails應用程序我需要確定在此形式表達某些URL路徑:用簡單的regex

paths = ['/a/*/b/c', '/f/*']

我在中間件和我訪問的路徑,是什麼我應該寫一些條件來檢查當前URL路徑是否與提供的數組中的條目匹配?

path = Rack::Request.new(env).path 
    included = paths.any? { |s| path.include?(s) } 

這只是檢查包含,但現在通配符已到達。

回答

2

您可以路徑轉換爲正則表達式模式:

paths = ['/a/*/b/c', '/f/*'] 

path = Rack::Request.new(env).path 
patterns = paths.map { |path| Regexp.new path.gsub(/\*/, '[^/]+') } 
    # Convert `*` to `[^/]+` to match any non-`/` characters. 
included = patterns.any? { |s| path =~ s }