Subscribed unsubscribe Subscribe Subscribe

Kentaro Kuribayashi's blog

Software Engineering, Management, Books, and Daily Journal.

Class::FluentInterface

id:secondlifeが「流れるようなインタフェイス!流れるようなインタフェイス!」とうるさいので、Perlでもやってみようと思って作ってみた。

泥酔しながらコード書いてたので、これでいいのかよくわかんない。オプションはhashref前提。

ともあれ、use base 'Class::FluentInterface'して、__PACKAGE__->fluentiate(qw(target_method fluent_method));とかする感じ。使い方はテスト参照。

use strict;
use warnings;
use Test::More qw(no_plan);

package Test::Class::FluentInterface;
use strict;
use warnings;
use base qw(Class::FluentInterface);

__PACKAGE__->fluentiate(qw(new fluent_new));
__PACKAGE__->fluentiate(qw(baz fluent_baz));

sub new {
    my ($class, $opt) = @_;
    bless $opt || {}, $class;
}

sub baz {
    my ($self, $arg, $opt) = @_;
    ($arg, $opt);
}

package main;

# Class method
isa_ok (Test::Class::FluentInterface->fluent_new, 'Class::FluentInterface::Proxy');
isa_ok (Test::Class::FluentInterface->fluent_new->foo('foo'), 'Class::FluentInterface::Proxy');
isa_ok (Test::Class::FluentInterface->fluent_new->foo('foo')->execute, 'Test::Class::FluentInterface');

my $obj = Test::Class::FluentInterface->fluent_new->foo('foo')->bar('bar')->execute;

is $obj->{foo}, 'foo';
is $obj->{bar}, 'bar';

# Instance method
isa_ok (Test::Class::FluentInterface->new->fluent_baz->hoge('hoge'), 'Class::FluentInterface::Proxy');

my ($baz, $opt) = Test::Class::FluentInterface->new->fluent_baz->hoge('hoge')->execute('baz');

is $baz, 'baz';
is $opt->{hoge}, 'hoge';