Created
February 14, 2013 06:52
-
-
Save Earlz/4951054 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//BarelyMVC Fluent Router API proof of concept | |
using System; | |
using System.Collections.Generic; | |
namespace tester | |
{ | |
class MainClass | |
{ | |
public static void Main(string[] args) | |
{ | |
var router=new Router(); | |
var blog=router.Controller(() => new BlogController()); | |
blog.Handles("/foo/bar").With((c) => c.View()); | |
Console.WriteLine(router.Execute("/foo/bar")); | |
Console.ReadKey(); | |
} | |
} | |
public class BlogController : HttpController | |
{ | |
public string View() | |
{ | |
return "meh"; | |
} | |
} | |
public class HttpController | |
{ | |
public string Foo{get;set;} | |
} | |
delegate T ControllerInvoker<T>(); | |
delegate string ControllerMethod<T>(T c); | |
class Router | |
{ | |
public Controller<T> Controller<T>(ControllerInvoker<T> invoker) where T:HttpController | |
{ | |
var c=new Controller<T>(this, invoker); | |
return c; | |
} | |
public List<Route> Routes{get;private set;} | |
public Router() | |
{ | |
Routes=new List<Route>(); | |
} | |
public string Execute(string url) | |
{ | |
foreach(var r in Routes) | |
{ | |
if(url==r.Pattern) | |
{ | |
return r.GetResponse(); | |
} | |
} | |
throw new ApplicationException(); | |
} | |
} | |
public class Route | |
{ | |
public string Pattern{get;set;} | |
public ResponseController GetResponse{get;set;} | |
} | |
class Controller<T> where T:HttpController | |
{ | |
ControllerInvoker<T> Invoker; | |
Router CurrentRouter; | |
public Controller(Router r, ControllerInvoker<T> invoker) | |
{ | |
CurrentRouter=r; | |
Invoker=invoker; | |
} | |
Route CurrentRoute; | |
public Controller<T> Handles(string pattern) | |
{ | |
CurrentRoute=new Route(); | |
CurrentRoute.Pattern=pattern; | |
CurrentRouter.Routes.Add(CurrentRoute); | |
return this; | |
} | |
public Controller<T> With(ControllerMethod<T> method) | |
{ | |
CurrentRoute.GetResponse=() => { | |
var c=Invoker(); | |
c.Foo=CurrentRoute.Pattern; | |
return method(c); | |
}; | |
return this; | |
} | |
} | |
public delegate string ResponseController(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment