plainblack.com
Username Password
search
Bookmark and Share
Subscribe

Macro Development Tutorial

A macro is a small Perl package that sits in the lib/WebGUI/Macro folder of your WebGUI install. You enable it by adding a line to your WebGUI config file.  Here is an example of a macro:

package WebGUI::Macro::HelloWorld;

use strict;

sub process {
    return "Hello World!";
}

1;

The above macro code would simply replace a macro like ^HelloWorld; with the text "Hello World!" (minus the quotes). You can see now how simple it is to create a macro.

In order to make a macro work, three things must be in alignment.

The first of the three is the package name. This can be found at the top of the macro file.
package WebGUI::Macro::HelloWorld;

The second is the filename of the macro.
lib/WebGUI/Macro/HelloWorld.pm

The third is the code component of the macro entry in the config file.
"HelloWorld" : "HelloWorld",

Notice how they all match in case, spelling, and spacing. This is very important. Without it, the macro would not work.

Passing In Parameters

Macros can have parameters passed into them. This is a two step process. First, when the macro is used it needs to pass in the parameters like this:

^Sum(12,5);

Second we, as programmers, must make use of the parameters, like this:

my ($session, $firstNumber, $secondNumber) = @_;

Here's an example macro that demonstrates the use of those parameters. The macro will accept two parameters, sum them, and return the result. So if we passed in 12,5 as parameters, we should get a result of 17.

package WebGUI::Macro::Sum;

use strict;

sub process {
    my ($session, $firstNumber, $secondNumber) = @_;
    return $firstNumber + $secondNumber;
}

1;

Let's take that a little further. Now let's accept N parameters and sum all of them no matter how many parameters there are. This will enable us to pass in 4,21,13,0,7,5 and get a result of 50.

package WebGUI::Macro::Sum;

use strict;

sub process {
    my ($session, @values) = @_;
    my $sum = 0;
    foreach my $value (@values) {
       $sum += $value;
    }
    return $sum;
}

1;

Macro Skeleton

To get started writing your own macro find the _macro.skeleton file in the lib/WebGUI/Macro folder. Copy it to a new name like MyMacro.pm. Then edit the first line in the file to match the file name, like:

package WebGUI::Macro::MyMacro;

That's it! Now you can start writing your very own macro.

Keywords: api Development macro tutorial

Search | Most Popular | Recent Changes | Wiki Home
© 2023 Plain Black Corporation | All Rights Reserved