Steve Jobs – Book Review

April 28th, 2012

I received Steve Jobs’ biography as a present last Christmas. I was never a fan of him or of Apple, and always found it annoying that he was praised as a great inventor and visionary. When he died, I was one of those saying “Hey, you know who also died? Dennis Ritchie, and he deserves way more recognition than Jobs.”

I expected the book to be another pile of adoration and I probably wouldn’t have even opened it if it wasn’t for a podcast that happened to pop up on my playlist a few weeks earlier. It was an interview with Walter Isaacson, the author of the biography, about his work on the book, and what it was like to work with Jobs when he was writing it.

In the interview, Isaacson told that Jobs asked him to write the biography a number of times, and he finally agreed under the condition that Jobs would not try to take control over it and would allow him to write a true story of his life. If this was true, I thought, then this could actually be a trustworthy biography and not another tribute to the greatest inventor of our times. So when the book got into my hands, I thought I might just as well read it and find out if Isaacson managed to keep it that way.

Well, he very much did. While it’s clear that Isaacson shows considerable respect to Jobs and all the things he managed to achieve, he also reveals his failures and weaknesses, and does not portray him as a superhero kind of figure. Jobs could be a real jerk to those around him, especially to the people that he worked with, and the biography does not pass over that.

The book also describes a good part of the history of home computers and technology in general. The first chapters, which cover the late seventies and early eighties, were almost a nostalgic read for me, since they brought back so many of my own memories from that time (well, the latter part of it, I’m not that old), when I was a little kid fascinated with those magical 8-bit machines.

But regardless of whether you get a kick out of early 80s computers or not, I recommend the biography, as if nothing else, it’s an excellently written, interesting, and sometimes even inspiring story. I truly enjoyed the read, and learned my lesson not to judge a book by how overrated and overpriced the products are that were created by its subject.

POD Functions Sort Greasemonkey Script

March 30th, 2012

Being a Perl programmer, I frequently visit CPAN or MetaCPAN to read Perl module documentation. I often go there to look up a specific function or method, and many modules are kind enough to list their functions/methods in the table of contents, so it’s usually easy to quickly find the one I’m looking for.

However, some of those kind modules list functions in non-alphabetical order, which is a bit less useful. Sure, that particular non-alphabetical order might make sense, for example when it groups functions by their purpose, but it still makes it harder to find a specific item on the list. Examples: DBI, DBIx::Class::Schema, DBIx::Class::Storage.

To cope with that, I wrote a small Greasemonkey script which allows you to sort those lists in alphabetical order. It tries to recognize lists of functions or methods using simple heuristicts (such as having a “_” in the list item text, or having no spaces) and puts an icon next to the list, which, upon clicked, sorts the list.

If you’re a Perl programmer with OCD, I’m sure you’ll love this script. Tested to work on Firefox and Chrome/Chromium.

File::PlainPath – Let Paths Be Paths Again

February 26th, 2012

The de facto standard way of constructing portable filesystem paths in Perl is through the use of File::Spec‘s catfile and catdir functions. Example:

my $path = File::Spec->catfile('dir', 'subdir', 'file.txt');

This method, or a similar one involving Path::Class, is the most recommended approach and has been adopted by application development frameworks like Dancer (which has a wrapper method for it, named path) and Catalyst (with its path_to method).

The slight problem that I see with this method is that it makes code a bit more complicated, and thus a bit less readable. Paths become lists of parameters and no longer look like paths.

I wrote a simple module that tries to address this by allowing you to write paths the traditional way — as strings, using a directory separator of your choice (/ being the default), while the catfile stuff happens behind the scenes. You can just say:

my $path = path 'dir/subdir/file.txt';

What it does is it splits the path string on each occurrence of the forward slash and feeds the resulting list of path components to File::Spec->catfile, which reassembles them using the appropriate OS-specific directory separator, and constructs the OS-specific path that you want.

The module is up on Github, and should also be available on CPAN shortly.

The Little Story of Opel

February 18th, 2012

Yesterday was World Cat Day (as observed in Poland), so I thought this might be the perfect time to tell you a little cat story.

More than two years ago, I posted the story of Rocket, a kitten that I found in my neighborhood — now a big, happy cat living with my parents. This story has a very similar beginning.

It was a cold September evening, I was walking home along a busy street, when I heard a kitten squeak. It was obviously coming from under a car parked near the street, so I started looking, but couldn’t see any kitten under the car. The squeaking continued, so I knew it must have been there, and I kept looking and reaching behind the wheels, but to no avail.

Since many people were passing by, my unusual activities attracted the attention of some of them. One man with an “excuse me sir, what are you doing?” look approached me, but before he even asked me a question, the kitten meowed again, so the man began searching with me.

After we both searched for a while with no success, the guy said “you know what, I live in this block here and I know the owner of this car, let me call him”. In a few minutes, the owner came and joined the search operation.

He looked inside the car just to be sure the kitten didn’t get in there in some miraculous way, but that was not the case. It was obvious that the little guy was somewhere in the car undercarriage, but the meowing seemed to be coming from different places and neither one of us was able to tell exactly where the kitten could be.

In the end, we lifted the car up with a jack, the owner crawled under it and saw some fur sticking out from a hollow spot next to the exhaust pipe. He reached in there and got the kitten out — the poor thing looked all dirty and miserable, but didn’t appear to be hurt in any way. The first guy called his wife, who brought some cat food (it turned out they had two Persian cats) and water for the rescuee.

Read the rest of this entry »

Six (Plus One) Android Apps that Make my Life Suck a bit Less

January 31st, 2012

I planned to write an introductory paragrah about how everyone and their grandma now uses mobile apps, but everyone (and their grandma) already knows that. So let me jump straight to the point — here’s a list of the apps that I found essential since I got myself an Android phone about one and a half year back.

1. K-9 Mail

A powerful e-mail client. Actually, it’s the e-mail client for your Android phone. Comes with a rich feature set that could put many desktop e-mail clients to shame. Has good support for multiple e-mail accounts, IMAP, signatures, PGP, searching — you name it. Highly recommended for everyone who wants to do some serious business with e-mail on their phone.

2. BeyondPod

A podcatcher/player. I’ve tried quite a few, and this one is by far the best. It’s loaded with useful features, but is still maintaining a clean user interface. This app is the top reason why I’ve become a regular listener of a number of podcasts, listening every day while driving, exercising, or doing mundane house chores.

3. OurGroceries

Dead simple app that aids you in putting together shopping lists. I was originally using the traditional paper and pen approach and thought that was all I’d ever need, but then I tried this app and it proved to be more effective. And, it adds that flavor of geekiness to the boring act of grocery shopping.

4. Twitter

The official Twitter client for Android. People used to criticize it and say that the unofficial apps are way better, but I’ve tried all of the popular ones and none of them offered anything particularly interesting to me. The official app is simple, has a clean interface, and does its job quite well.

5. c:geo

A great geocaching app with lots of useful features and a nice user interface. If you want to try geocaching with your Android phone and are looking for an app, look no further and get c:geo.

6. APNdroid

A tiny app with a very specific purpose. All it does is it lets you add a button to your home screen to toggle mobile data connection on and off, making a commonly used feature accessible immediately, instead of forcing you to find it buried somewhere in the settings menu.

Honorable mention: Shuffle

A simple but effective Getting Things Done app. I started implementing GTD a while ago when a guy I worked with told me about it, and he also recommended this app. I didn’t place it on the list, because the current version has a significant flaw — it fails to properly synchronize with Tracks, a GTD web application that I use on the desktop machine, and I can’t really use it until that bug gets fixed (hopefully, soon).

Alternative Dancer Templating Engines

December 18th, 2011

Dancer uses a simple model of interfacing with templating engines (based on Dancer::Template::Abstract) and makes it very easy to add support for new engines. Thanks to this, if you’re not happy with the default simple engine or with Template Toolkit, there is now a dozen different alternatives to choose from. Let’s take a look at some of them.

Dancer::Template::Tiny

Template::Tiny is a lightweight engine which reimplements a subset of Template Toolkit features. As the name implies, it aims to accomplish this with as little code as possible. If you’re using just the basic functionality of Template Toolkit, you should be able to switch to Template::Tiny without any modifications to template files (and you can easily go back at any moment).

Dancer::Template::Tiny is going to replace Dancer::Template::Simple as the default templating engine in Dancer2.

Example template:

<html>
  <head>
    <title>Tiny Example</title>
    <link rel="stylesheet" href="[% request.uri_base %]/css/style.css" />
  </head>
  <body>
    <h1>Hello, World! This is Dancer [% dancer_version %]!</h1>
    <p>
      [% IF morning %]
        Good morning!
      [% ELSE %]
        Good afternoon!
      [% END %]
    </p>
  </body>
</html>

Route handler:

use DateTime;
   
get '/hello' => sub {
    template 'hello', { morning => (localtime)[2] < 12, now => DateTime->now };
};

Dancer::Template::Tenjin

Tenjin is a very fast templating engine with implementations for many languages — including, of course, Perl. Its great performance comes from the fact that it uses the underlying language’s constructs to process templates, instead of defining its own templating language and having to parse it. Support for this engine in Dancer is provided by Dancer::Template::Tenjin.

Example template:

<html>
  <head>
    <title>Tenjin Example</title>
    <link rel="stylesheet" href="[== $request->uri_base =]/css/style.css" />
  </head>
  <body>
    <h1>Hello, World! This is Dancer [= $dancer_version =]!</h1>
    <p>
      <?pl if ((localtime)[2] < 12) { ?>
        Good morning!
      <?pl } else { ?>
        Good afternoon!
      <?pl } ?>
    </p>
    <p>
      Current time is: [== DateTime->now->hms =]
    </p>
  </body>
</html>

Route handler:

use DateTime;
   
get '/hello' => sub {
    template 'hello';
};

Dancer::Template::Haml

Haml, which stands for “HTML Abstraction Markup Language”, brings a fresh, different approach to templating. It aims at making templates short, clean, and as easy to read as well-formatted source code. Dancer::Template::Haml is a wrapper around Text::Haml and lets you use Haml templates in Dancer applications.

Example template:

%html
  %head
    %title Haml Example
    %link(rel="stylesheet" href="#{$request->uri_base}/css/style.css")
  %body
    %h1 Hello, World! This is Dancer #{$dancer_version}!
    %p
      - if ((localtime)[2] < 12) {
        Good morning!
      - } else {
        Good afternoon!
      - }
    %p Current time is: #{DateTime->now->hms}

Route handler:

use DateTime;
   
get '/hello' => sub {
    template 'hello';
};

More

There are many more interesting templating engines ready to be used with Dancer, such as Mason (provided by Dancer::Template::Mason) or Xslate (Dancer::Template::Xslate). Do a CPAN or MetaCPAN search for “dancer template” to get a list of all the available engines, and choose the one that suits you best. In the true spirit of Perl, there’s more than one way to write a template!

This post was originally published as part of the 2011 Dancer Advent Calendar.

Serving Files with Dancer::Plugin::DirectoryView and Dancer::Plugin::Auth::Htpasswd

December 13th, 2011

A while ago I was converting a simple PHP website to Dancer, and moving it from being deployed on Apache to Starman. There wasn’t a lot of code, so rewriting went quickly — but, the site used a few specific features of Apache, namely directory indexes (courtesy of mod_autoindex) to allow user access to directories/files on the server, and htpasswd files to password-protect some of those directories.

I could just deploy the new Dancer website on Apache and keep using those goodies, but I thought that it would be nice if Dancer itself provided similar features. So, I created two plugins that do just that: Dancer::Plugin::DirectoryView and Dancer::Plugin::Auth::Htpasswd. Let me now show you how to use them.

Directory Indexes

Let’s say we have a files directory under public, and we’d like to allow users to browse it and download files. Enabling directory access is as simple as including the plugin in our Dancer application:

      package MyWebApp;

      ...

      use Dancer::Plugin::DirectoryView;

And updating the configuration file (config.yml) to tell the plugin which directory should be made available, and at which URL:

      plugins:
          DirectoryView:
              url: /pub
              root_dir: files

That’s it — now, if we launch our app and point the browser at the /pub URL, we’ll see the contents of the directory:

Protecting Directories with Htpasswd Files

As you might have noticed on the screenshot, there’s a secret directory under files. It contains some super secret data that should only be available to authorized users, so now we’re going to protect it using a htpasswd file.

First, let’s create the htpasswd file and an user, named “alice”:

      $ htpasswd -c htpasswd alice

Once it is created, we need to put the htpasswd file in a safe location outside of the public directory, so let’s create a new directory passwd and store the file in there.

(If you’re migrating from Apache and already have the htpasswd file, you just need to copy it to your Dancer application.)

In our Dancer application, we include the Auth::Htpasswd plugin:

      package MyWebApp;

      ...

      use Dancer::Plugin::Auth::Htpasswd;

Now, we need to update our configuration file and add settings for the plugin. We’ll tell it to protect the /pub/secret path, and to use the htpasswd file we just created:

      plugins:
         "Auth::Htpasswd":
             paths:
                 "/pub/secret":
                     realm: "Secret Files"
                     passwd_file: passwd/htpasswd

The realm parameter lets us set the text that will be shown to the user in the login window displayed by the browser.

Let’s see if our protection works. We restart the application and try to access the /pub/secret/ URL:

Great, our confidential files are safe. Only when we log in as “Alice”, we’ll be able to access them:

This post was originally published as part of the 2011 Dancer Advent Calendar.

GitHub-friendly README files with ExtUtils::MakeMaker and Module::Build

November 30th, 2011

GitHub is a great place to host open-source projects and expose them to a wide community of developers, so it’s not surprising that more and more Perl modules are making it their home.

One of the features of GitHub is that it checks if a repository has a README file in its root directory, and displays it on the home page of the repository. This makes the README file a good place to introduce your project to the public.

GitHub also understands a number of markup languages, such as Markdown and Textile, and if the README file is in one of these formats, it will be transformed into nicely formatted HTML. One of the supported formats is POD, which means that the standard documentation of a Perl module can be used as its README file and serve as the repository’s home page (much like on CPAN).

Module::Starter, which is Perl’s recommended tool for building modules, does not create a GitHub-friendly README file — instead, the README that it produces contains installation instructions (the "perl Makefile.PL; make..." mantra) and a couple links to module resources. This means that if you want to have a GitHub-friendly README file in your module, you need to either create it yourself, or tweak your build script a bit to have it generate it for you automatically.

This article wouldn’t be particularly interesting if I told you to now go and make the README file yourself, would it? So let me show you how to do this automatically with ExtUtils::MakeMaker and Module::Build based modules (generated with Module::Starter). I will demonstrate how to create two README files: one being the POD version (named README.pod), the other one plain text (named just README).

ExtUtils::MakeMaker

Since ExtUtils::MakeMaker creates a Makefile with shell commands, you can tell it to generate the README files using two core Perl command-line utilities: perldoc (to generate POD from module’s source) and pod2text (to convert POD into plain text). Extend Makefile.PL by adding the shell commands as the PREOP attribute of the dist target configuration:

my $preop =
    'perldoc -uT $(VERSION_FROM) | tee $(DISTVNAME)/README.pod > README.pod;' .
    'pod2text README.pod | tee $(DISTVNAME)/README > README';

WriteMakefile(
    NAME                => 'Foo::Bar',
    AUTHOR              => q{Michal Wojciechowski <odyniec@cpan.org>},
    VERSION_FROM        => 'lib/Foo/Bar.pm',
    ABSTRACT_FROM       => 'lib/Foo/Bar.pm',
    ($ExtUtils::MakeMaker::VERSION >= 6.3002
      ? ('LICENSE'=> 'perl')
      : ()),
    PL_FILES            => {},
    PREREQ_PM => {
        'Test::More' => 0,
    },
    dist                => {
        COMPRESS => 'gzip -9f',
        SUFFIX => 'gz',
        PREOP => $preop,
    },
    clean               => { FILES => 'Foo-Bar-*' },
);

Now, when you run perl Makefile.PL and make dist, the two README files will be created for you.

Don’t worry if running make dist produces warnings that README and README.pod are missing — it’s no big deal, as the warnings will only be seen by you when making a distribution package, and not by the user building the module.

Module::Build

Module::Build defines a docs action, and it’s the appropriate place for the code that builds the README files. Two modules that you can use for this purpose are Pod::Select and Pod::Readme. In your Build.PL file, create a subclass of Module::Build, and define a subroutine named ACTION_docs, similar to the one shown below:

my $class = Module::Build->subclass(
    class => 'My::Builder',
    code => q{
        sub ACTION_docs {
            use Pod::Readme;
            use Pod::Select;

            my $self = shift;

            podselect({ -output => 'README.pod' },
                'lib/Foo/Bar.pm');

            my $parser = Pod::Readme->new();
            $parser->parse_from_file('README.pod', 'README');

            return $self->SUPER::ACTION_docs;
        }
    }
);

my $builder = $class->new(
    module_name         => 'Foo::Bar',
    license             => 'perl',
    dist_author         => q{Michal Wojciechowski <odyniec@cpan.org>},
    dist_version_from   => 'lib/Foo/Bar.pm',
    requires => {
        ...
    },
    configure_requires => {
        'Pod::Readme' => 0,
        'Pod::Select' => 0,
    },
    build_requires => {
        'Pod::Readme' => 0,
        'Pod::Select' => 0,
        'Test::More' => 0,
    },
    add_to_cleanup      => [ 'Foo-Bar-*' ],
    create_makefile_pl => 'traditional',
);

$builder->create_build_script();

You can now run perl Build.PL, and then ./Build docs, to build the README files.

Remember to add the Pod::Select and Pod::Readme modules to configure_requires and build_requires, as shown in the above example.

Installation instructions

Since these methods overwrite the original README file provided by Module::Starter, the installation instructions in it are also lost. It’s a good practice to always include installation instructions, so go ahead and add an INSTALL file to your module’s distribution files. It can be really simple and straight to the point:

Foo-Bar

INSTALLATION

To install this module, run the following commands:

    perl Build.PL
    ./Build
    ./Build test
    ./Build install

Finally, remember to add README.pod and INSTALL to your module’s MANIFEST.

Busy Busy Me

October 31st, 2011

Things have been slow with my projects in the past few weeks, and that’s because most of my time is now consumed by dayjob. I’m currently working on two part-time contracts, one being a telecommute Perl job for a client in London, the other one an enterprisey Java web project here in Warsaw. This translates to roughly 11-12 hours of work a day, and while I’m used to working this many hours, there’s obviously not much time left for other things.

I hope things will settle down a bit in the next couple of days (especially with the Java project, which should go out of the hot initiation phase it’s currently in), and I’ll have more time for my stuff — especially that I have a lot of updates planned for my jQuery plugins and CPAN modules. For now, I’m trying to squeeze out a few hours every week to at least do some minor updates. So yesterday, I managed to push out a new release of Dancer::Plugin::DirectoryView.

Apologies to everyone who contacted me by e-mail (or other means) and didn’t get a reply, I promise in the next few days I’ll go through my mailbox and respond to any unanswered messages. As a general rule: if you don’t get a response from me in a day or two, feel free to write me again — it usually works.

Dancer::Plugin::Auth::Htpasswd

October 11th, 2011

I have developed a new Dancer plugin based on the recently-released Dancer::Plugin::Auth::Basic. The new one is called Dancer::Plugin::Auth::Htpasswd, and it serves the same purpose as Auth::Basic, which is adding basic HTTP authentication to a Dancer web app — the difference is that Auth::Htpasswd does this using Apache-style htpasswd files.

The plugin might be useful if you’re migrating a web application from Apache to a different HTTP server and want to keep using the same htpasswd files, or if you don’t want to keep passwords written in plain text in configuration (as it is with Auth::Basic).

Get the plugin on CPAN and on Github.