Skip to content
Browse files

first commit

  • Loading branch information...
0 parents commit d81bf0de8da276bd8bda31c611efaef865b928f0 @kazuho committed Sep 22, 2010
Showing with 78 additions and 0 deletions.
  1. +49 −0 lib/Text/Transformer.pm
  2. +29 −0 t/00base.t
49 lib/Text/Transformer.pm
@@ -0,0 +1,49 @@
+package Text::Transformer;
+
+use strict;
+use warnings;
+
+use Regexp::Assemble;
+
+sub new {
+ my $klass = shift;
+ die "# of arguments is not even"
+ unless @_ % 2 == 0;
+ my $self = bless {
+ handlers => [],
+ default_handler => sub { $_[0] },
+ };
+ my $ra = Regexp::Assemble->new();
+ while (@_) {
+ my $pattern = shift;
+ my $subref = shift;
+ if ($pattern ne '') {
+ $ra->add($pattern);
+ push @{$self->{handlers}}, [ qr/$pattern/, $subref ];
+ } else {
+ $self->{default_handler} = $subref;
+ }
+ }
+ my $assembled = $ra->re;
+ $self->{match} = qr/($assembled)/;
+ return $self;
+}
+
+sub transform {
+ my ($self, $text) = @_;
+ my @ret;
+ for my $token (split /$self->{match}/, $text) {
+ for my $handler (@{$self->{handlers}}) {
+ if ($token =~ /$handler->[0]/) {
+ push @ret, $handler->[1]->($token);
+ goto NEXT_TOKEN;
+ }
+ }
+ push @ret, $self->{default_handler}->($token);
+ NEXT_TOKEN:
+ ;
+ }
+ return join '', @ret;
+}
+
+1;
29 t/00base.t
@@ -0,0 +1,29 @@
+use strict;
+use warnings;
+
+use HTML::Entities;
+use Test::More;
+
+use_ok('Text::Transformer');
+
+my $tf = Text::Transformer->new(
+ 'http://[A-Za-z0-9_\.\%\?\#\@/]+' => sub {
+ my $url = shift;
+ qq{<a href="@{[encode_entities($url)]}">@{[encode_entities($url)]}</a>};
+ },
+ '\@[A-Za-z0-9_]+' => sub {
+ my $name = shift;
+ $name =~ s/^\@//;
+ qq{<a href="http://twitter.com/@{[encode_entities($name)]}">\@$name</a>};
+ },
+ '' => sub {
+ my $text = shift;
+ encode_entities($text);
+ },
+);
+is(
+ $tf->transform('@kazuho http://hello.com/ yesyes <b>'),
+ '<a href="http://twitter.com/kazuho">@kazuho</a> <a href="http://hello.com/">http://hello.com/</a> yesyes &lt;b&gt;',
+);
+
+done_testing;

0 comments on commit d81bf0d

Please sign in to comment.
Something went wrong with that request. Please try again.