PrePAN

Sign in to PrePAN

Text::Composer Handy Text Builder with Parameters and Logics

Author
i110@github
Date
URL
https://github.com/i110/Text-Composer
Status
In Review
Good

Synopsis

# See below

Description

DESCRIPTION

I couldn't find nice modules which can handle parameterized text. Please let me know if you know similar modules.

SYNOPSIS

use Text::Composer;
my $composer = Text::Composer->new(
    start_symbol => '{{',
    end_symbol => '}}',
    recursive => 1,
);

say $composer->compose('My name is {{ name }}', +{ name => 'i110' });
# 'My name is i110'

say $composer->compose('My name is {{ name }}', +{
    name => '{{prefix}} i110',
    prefix => 'Mr.',
});
# 'My name is Mr. i110'

say $composer->compose('\{\{ escaped \}\} key will not be expanded', +{
    escaped => 'gununu',
});
# '{{ escaped }} key will not be expanded'

say $composer->compose('{{ with_complicated_logic }}', +{
    with_complicated_logic => sub {
        my ($self, $key) = @_;
        "This text was composed $key by {{ twitter_id }}";
    },
    twitter_id => sub {
        '@{{ user_name }}';
    },
    user_name => 'i110',
});
# 'This text was composed with_complicated_logic by @i110'

use Text::Composer qw(compose_text);
compose_text('{{without_oo_interface}}', +{ without_oo_interface => 'hakadoru' });
# 'hakadoru'

METHODS

  • new ( %args )

    • $recursive

      Expand parameters recursively. Default is true.

    • $start_symbol

    • $end_symbol

      Delimiters for parameters. Defaults are '{{' and '}}', respectively.

  • compose ( $template, $params )

    Compose rext using a template and parameters.

    • $template

      Parameterized text. Required.

    • $params

      Parameters which will be rendered in the template. This must be a hashref or coderef, otherwise it will throw an exception. And also, hash's values must be a scalar or coderef, otherwise it will throw an exception. Both of these coderefs take the same two arguments, Text::Composer instance itself and the accessing key, and should return a scalar or coderef. If the return value is a coderef, it will be called again (and repeat this process until you get a scalar value).

Comments

Have you tried Text::Template?
While nowhere near as complex as what you are suggesting here, in the context of string translations you might find that the "__x" function in Locale::TextDomain already does what you want.
Thank you for your comments, ernix and mlawren. I checked Text::Template and Locale::TextDomain, but there seems to be no modules which can replace strings recursively (like above). I noticed that the main benefit of this module (and what I really want) is the recursion, so I'm considering renaming this module to "Text::Template::Recursive". I'd like your opinion on this if you have.

Please sign up to post a review.