In the spirit of Rails, let's create a config/routes.rb
file so we have a Rails-like structure. This file contains our application routes.
# config/routes.rb
require_relative '../router'
Router.draw do
get('/') { "Akshay's Blog" }
get('/articles') { 'All Articles' }
get('/articles/1') { "First Article" }
end
Note that we're calling the draw
method on the Router
and passing a block. Ruby will execute this block (code within do..end
above) in the context of the instance of the Router
. Hence, the self
object in that block will be the Router
.
The above code is similar to:
router = Router.new
router.get('/') { "Akshay's Blog" }
# and so on...
Don't you just love metaprogramming in Ruby?
If you're curious to learn more about metaprogramming, check out my summary of Paolo Perrotta's excellent book: Metaprogramming Ruby 2
There's only one thing remaining. Use those routes!