Skip to content

Instantly share code, notes, and snippets.

@tadzik
Created November 21, 2010 00:00
Show Gist options
  • Save tadzik/708292 to your computer and use it in GitHub Desktop.
Save tadzik/708292 to your computer and use it in GitHub Desktop.
grammar Mysite {
token TOP {
<main> |
<about> |
<contact> |
<cookie> |
<api> |
<e404>
}
token main { ^ '/' $ }
token about { ^ '/about' $ }
token contact { ^ '/about/contact' $ }
token cookie { ^ '/cookie' $ }
token api { ^ '/api/' $<type>=[ \S ]+ $ }
token e404 { }
}
class Mysite::Actions {
method TOP($/) {
make $/.values[0].ast;
}
method main($/) { make "Hello from the main page!" }
method about($/) { make "About me" }
method contact($/) { make "Reach me at 555 01 23" }
method cookie($/) { make $*REQUEST.cookie }
method api($/) {
given $<type>.Str {
when 'json' { make '{"foo":"bar"}' }
when 'xml' { make '<foo>bar</foo>' }
default { make 'Wrong serialization method passed' }
}
}
method e404($/) { make "404: Not found" }
}
class Request is Cool {
has $.path;
has $.cookie;
method Str {
$.path
}
}
my ($*REQUEST, $req, $res);
$*REQUEST = $req = Request.new(path => '/cookie', cookie => 'monster');
$res = Mysite.parse($req, :actions(Mysite::Actions.new));
say $res.ast;
$*REQUEST = $req = Request.new(path => '/nope');
$res = Mysite.parse($req, :actions(Mysite::Actions.new));
say $res.ast;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment