Search code examples
ruby-on-railsdjangoperlroutesurl-routing

Rails or Django style routing in Perl


I have grown accustomed to the way Rails maps a route or the Django uses regex on a route (I am not expect in Django, but this is what I have heard how it does it's routing) and how they use the style of permalinks to access a particle web page. Is it possible to do the same thing in Perl?


Solution

  • I think the Perl web framework with most Rails-like routing would be Mojolicious

    The creator of Mojolicious did write an excellent blog post called "Dispatchers for dummies" comparing the major Perl, Ruby & Python web frameworks and highlighting what he believed were improvements he made with routing on Mojolicious.

    Unfortunately above post is no longer online :( Instead you have to settle for the Mojolicious::Guides::Routing documentation. Here is a routing example from the docs:

    package MyApp;
    use base 'Mojolicious';
    
    sub startup {
        my $self = shift;
    
        # Router
        my $r = $self->routes;
    
        # Route
        $r->route('/welcome')->to(controller => 'foo', action => 'welcome');
    }
    
    1;
    


    There are also other Perl frameworks which provide direct URL to action routing:

    A more complete list of Perl web frameworks can be found on the Perl5 wiki


    And if you are framework adverse then take a look at Plack (also see PSGI wikipedia). This is same as Rack on Ruby and WSGI on Python.

    Here is a quick and dirty example of Plack:

    use 5.012;
    use warnings;
    
    my $app = sub {
        my $env = shift;
    
        given ($env->{PATH_INFO}) {
    
            return [ 200, [ 'Content-Type' => 'text/plain' ], [ 'Hello Baz!' ] ]
                when '/hello/baz';
    
            default {
                return [ 200, [ 'Content-Type' => 'text/plain' ], [ 'Hello World' ]];
            }
        }
    }
    

    Then use plackup above_script.psgi and away you go.