Skip to content

Instantly share code, notes, and snippets.

@marshall-lee
Last active April 28, 2019 11:31
Show Gist options
  • Save marshall-lee/615642d1ee57754e2e5ef0fc20bf10e9 to your computer and use it in GitHub Desktop.
Save marshall-lee/615642d1ee57754e2e5ef0fc20bf10e9 to your computer and use it in GitHub Desktop.
def build(str)
str = str.dup
str.prepend '\A'
str.gsub! %r{/:([a-z]+)}, '/(?<\1>[^\/]+)'
str << '(?<format>\.[a-z]\w*)?'
str << '\z'
Regexp.new(str)
end
rx = build('/posts/:id/comments')
m = rx.match('/posts/123/comments')
puts m[:id] # 123
m = rx.match('/posts/123/comments.html')
puts m[:id] # 123
puts m[:format] # .html
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment