Parsing Parameters for Liquid Blocks

One of the first things I noted when I posted (some would say borderline complaining) about my first encounters with Liquid - the templating engine used in Mephisto and a few other apps - was the way it didn’t seem to abstract how parameters were set on the block.

Well, turns out it’s not quite so nasty as I first expected - you indeed don’t have to write all the regular expressions yourself. Inside liquid.rb a number of constants are defined, a lot of these are to do with capturing aspects of the tag.

One such regular expression is for TagAttributes, so we can write a test that:

def test_should_use_parameterised_url_for_feed  template = Liquid::Template.parse(    "{% flickrphotostream feed: http://blah/test.xml %}    {% endflickrphotostream %}")  first_block = template.root.nodelist.first      assert_equal 'http://blah/test.xml', first_block.feed_urlend

first_block is the first block that we encounter in our template - the Flickr photostream one. Inside our class, we can then build up an attributes hash from these items using the TagAttributes regular expression as follows:

markup.scan(Liquid::TagAttributes) do |key, value|  @attributes[key.to_sym] = valueend

Hey presto, we’re done.

Now, I’m not so sure I like this too much, it doesn’t feel very Rails-like. Too much dealing with regular expressions for my liking.

So, I’m going to continue refactoring my solution (please don’t read too much into the tests or code I’ve written so far, it’s very much a first stab over the course of a little hacking). As part of that, I’d definitely like to see if I can Rails-ActiveRecord-it-up a tad, a la:

class FlickrPhotoStream < Liquid::Block  attr :feed_url, :count

Maybe I’ll give that a go tomorrow.