Skip to content

Instantly share code, notes, and snippets.

@kenpusney
Last active December 16, 2015 19:09
Show Gist options
  • Save kenpusney/5482584 to your computer and use it in GitHub Desktop.
Save kenpusney/5482584 to your computer and use it in GitHub Desktop.
simple router for method dispatching
class Router
def initialize
@router = []
end
def reg(path,&block)
@router << { :path => path, :block => block}
end
def fetch(url)
@router.each do | rtr |
if url =~ /#{rtr[:path]}/
rtr[:block].call url
end
end
end
alias_method :[],:fetch
end
## new
router = Router.new
## add router
## do ... end block may replaced by SomeClass.new
router.reg "/hello" do |url|
puts "Hello, world!"
end
## fetch url
router['/hello']
## => Hello, world!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment