mruby binding for libr3, a high-performance path dispatching library.
tree << '/users/{user_id}/feeds/{feed_id}'
tree.match '/users/1/feeds/2'
# => { user_id: '1', feed_id: '2' }
Add the line below to your build_config.rb
:
MRuby::Build.new do |conf|
# ... (snip) ...
conf.gem mgem: 'mruby-regexp-pcre' # Optional
conf.gem mgem: 'mruby-r3'
end
Or add this line to your aplication's mrbgem.rake
:
MRuby::Gem::Specification.new('your-mrbgem') do |spec|
# ... (snap) ...
spec.add_dependency 'mruby-regexp-pcre' # Optional
spec.add_dependency 'mruby-r3'
end
First of all a tree object has to be created.
tree = R3::Tree.new
The size grows dynamically. However the initializer accepts an optional initial size. The default initial size is up to 5 routes.
tree = R3::Tree.new(100)
The pattern syntax for routes is the following. Enhanced support for regular expression requires mruby-regexp-pcre to be installed!
/blog/post/{id} use [^/]+ regular expression by default.
/blog/post/{id:\d+} use `\d+` regular expression instead of default.
Routes can be added to the tree at any time, however dont forget to call compile before using them.
tree << '/'
tree << '/blog/post'
tree << '/blog/post/{id}'
tree << '/user/{user_id}/feeds/{feed_id}'
Its also possible to specify the HTML method rather then to allow any.
tree.add('/blog/post/{id:\\d+}', R3::DELETE)
Once the tree has been compiled he's ready for dispatching.
tree << '/'
tree.add '/users', R3::ANY
tree.add '/posts', R3::GET
tree.add '/users/{user_id}/feeds/{feed_id}', R3::GET
tree.compile
tree.routes
# => ['GET /users/{user_id}/feeds/{feed_id}', ...]
tree.match? '/'
# => true
tree.match '/'
# => {}
tree.match? '/other'
# => false
tree.match '/other'
# => nil
tree.match? '/users', R3::POST
# => true
tree.match? '/posts', R3::POST
# => false
tree.match '/users/1/feeds/2'
# => { user_id: '1', feed_id: '2' }
tree.match '/users/1/feeds/2', R3::POST
# => nil
Before you're writing your own URL map, you can make use of the built-in feature to add any kind of data with the route.
tree.add('/user/{name}', R3::ANY, -> { 'callback handler' })
tree.compile
params, handler = tree.match('/user/bernd')
handler.call
# => 'callback handler'
Clone the repo:
$ git clone https://github.com/katzer/mruby-r3.git && cd mruby-r3/
Compile the source:
$ rake compile
Run the tests:
$ rake test
- Add a route for multiple HTTP methods.
- missing asprintf() for MingGW 32-bit compiler.
- Sebastián Katzer, Fa. appPlant GmbH
The mgem is available as open source under the terms of the MIT License.
Made with 😋 from Leipzig
© 2017 appPlant GmbH