user3452713
user3452713

Reputation: 140

Dancer2::Plugin creation

I am trying to create a plugin for Dancer2, and set the options in the config.yml file. My config.yml file looks like this:

 plugins:
      Test:
        foo: 1
        bar: 2
        baz: 3

I am trying to read these values via plugin_setting(), without success. In the line:

my $settings = plugin_setting();

$settings gets no value. I expect to get foo: 1, bar: 2, baz: 3.

My code is the following:

package Dancer2::Plugin::Test;

use Dancer2::Plugin;
use Data::Dumper;

our $VERSION = 0.01;

my $settings = plugin_setting();

register foo => sub {
    return my $settings = _get_settings();
};

register_plugin for_versions => [ 2 ] ;

sub _get_settings {
    my $args = {};
    for (qw/foo bar baz/) {
        if (exists $settings->{$_}) {
        open A, q[>], 'settings.txt';
            $args->{$_} = $settings->{$_};
        }
    }
    print A Dumper $args;close A;
    return $args;
}
1;

Anyone could help me?

Upvotes: 1

Views: 116

Answers (1)

vanHoesel
vanHoesel

Reputation: 954

Dancer has done a complete overhaul with their plugins, please see their Dancer2::Plugin documentation.

Here I show you a simple example:

package Dancer2::Plugin::Test;

use strict;
use warnings;

use Dancer2::Plugin;

has dictionary => (
    is             => 'ro',
    from_config    => 'dict',
    plugin_keyword => 'foo',
);

1;

and inside the config.yml:

plugins:
    Test:
        dict:
            foo: 1
            bar: 2
            baz: 3

This way, you can use 'plugin top-level' configuration, from which I would assume you 'know' the keys; a config from which you do not know what keys are there would be a bit difficult to parse. In that top-level I created a dictionary key dict, which on its turn can hold an unknown list of key-value pairs.

Inside your plugin, you can use $plugin->dictionary to access the (internal) hash.

Inside a Dancer route, you can simply use foo(), as you have declared is to be a keyword.

I think the developers have done well, making the plugins look very clean!

Upvotes: 2

Related Questions