Subject: | truncate on space |
Date: | Mon, 07 Apr 2008 10:42:37 +0200 |
To: | bug-html-truncate [...] rt.cpan.org |
From: | Lorenzo Iannuzzi <lorenzo.iannuzzi [...] staff.dada.net> |
Hi Ashley,
I found your module useful. Tho only thing it lacked to me was the
option to truncate on word boundaries, without leaving "breaked" words.
I added an option to do this, see the patch. I also noted that, despites
what's in the documentation, chars limit doesn't take into account ellipsis.
Thanks for your work and sorry me if I made some mistakes.
Lorenzo Iannuzzi
Skype: innakis
Index: C:/Documents and Settings/l.iannuzzi/Documenti/workspace/importer/lib/HTML/Truncate.pm
===================================================================
--- C:/Documents and Settings/l.iannuzzi/Documenti/workspace/importer/lib/HTML/Truncate.pm (revision 4366)
+++ C:/Documents and Settings/l.iannuzzi/Documenti/workspace/importer/lib/HTML/Truncate.pm (working copy)
@@ -103,6 +103,7 @@
_repair => undef,
_skip_tags => \%skip,
_stand_alone_tags => \%stand_alone,
+ _space_truncation => undef,
}, $class;
while ( my ( $k, $v ) = splice(@_, 0, 2) )
@@ -137,7 +138,7 @@
=head2 $ht->chars
Set/get. The number of characters remaining after truncation,
-including the C<ellipsis>. The C<style> attribute determines whether
+excluding the C<ellipsis>. The C<style> attribute determines whether
the chars will only count text or HTML and text. Only "text" is
supported currently.
@@ -350,7 +351,12 @@
if ( $length > $chars )
{
- $self->{_renewed} .= substr($txt, 0, ( $chars ) );
+ $txt = substr($txt, 0, ( $chars ) + 1 );
+ if ( $self->{_space_truncation} )
+ {
+ $txt =~ s/(.*)\s*\b.*$/$1/;
+ }
+ $self->{_renewed} .= $txt;
$self->{_renewed} =~ s/\s+\Z//;
$self->{_renewed} .= $self->ellipsis();
last TOKENS;
@@ -430,6 +436,26 @@
}
}
+=head2 $ht->space_truncation
+
+Set/get, true/false. If true, will attempt to truncate on word boundaries,
+i.e. on last occurring space before truncation limit.
+
+=cut
+
+sub space_truncation {
+ my $self = shift;
+ if ( @_ )
+ {
+ $self->{_space_truncation} = shift;
+ return 1; # say we did it, even if untrue value
+ }
+ else
+ {
+ return $self->{_space_truncation};
+ }
+}
+
#
sub _load_chars_from_percent {