Friday, February 7, 2014

Expanding the Use of Perl Plugins

The <plugin> tag allows you create Perl classes that provide specific functionality for your pages.  But what about using CPAN modules as plugins?  Most CPAN modules that have a new() constructor can be used as plugins.  One of my favorite CPAN modules is Text::CSV_XS so it was disappointing to find I had some issues with this one.


Bedrock has had a limitation on using some CPAN modules because of the way Bedrock coerces lists into Bedrock array objects when invoking method calls on objects...until now.

Because Bedrock treats pretty much all basic types (scalars, hashes, and arrays) as objects, Bedrock coerces lists into arrays when they are sent back from method calls to your page.

Hence, a method of an object that returns a list, would present in Bedrock as an array object.  That's actually useful and what you want most of the time.  This allows you to invoke some very useful methods for array objects on that new entity that you just created.

  <null:foo $my_plugin.some_method()>

  <if $foo.length() >
    --- something useful ---
    <raise "foo is empty">

However, a problem arises when you really want a list because a list is what your CPAN module wants.


  <null:line 1 2 3 4 "Hello World">
  <null $TextCSV_XS.combine($line)>
  <var $TextCSV_XS.string()>

In order to use this CPAN module, I could write my own custom plugin, subclass Text::CSV_XS and provide my own combine() method that takes array references.  Too much work!

To mitigate this issue Bedrock array objects now provide the list() method that allows you to force Bedrock to return a list and avoid the coercion to an array object that would normally occur during a method call.

  <null $TextCSV_XS.combine($line.list())>
  <var $TextCSV_XS.string()>

The list() method can also take an array object as an argument and return that object as a list instead.  This pattern may be more useful in certain circumstances.

  <null $TextCSV_XS.combine($dummy.list($line))>
  <var $TextCSV_XS.string()>


Good Bedrock pages do not contain a lot of what looks like code.  If you find yourself writing code, you should bury that in a plugin that provides a core set of methods or attributes for your front end web developer.  Using CPAN modules or create more complex constructions that look like code is fine when prototyping...but BBP (Bedrock Best Practices?) compels us to ease up on the code and keep our HTML pages free of that kind of clutter.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.