Skip to content

Instantly share code, notes, and snippets.

@hidek
Created September 8, 2009 05:55
Show Gist options
  • Select an option

  • Save hidek/182742 to your computer and use it in GitHub Desktop.

Select an option

Save hidek/182742 to your computer and use it in GitHub Desktop.
package DBIx::Class::EncodeColumns;
use strict;
use warnings;
use base qw/DBIx::Class/;
use Encode qw/encode decode is_utf8/;
__PACKAGE__->mk_classdata('_encode_columns');
__PACKAGE__->mk_classdata('in_encoding');
__PACKAGE__->mk_classdata('out_encoding');
=head1 NAME
DBIx::Class::UTF8Columns - Force UTF8 (Unicode) flag on columns
=head1 SYNOPSIS
package Artist;
__PACKAGE__->load_components(qw/UTF8Columns Core/);
__PACKAGE__->encode_columns(qw/name description/);
__PACKAGE__->in_encoding('utf8');
__PACKAGE__->out_encoding('CP932');
# then belows return strings with utf8 flag
$artist->name;
$artist->get_column('description');
=head1 DESCRIPTION
This module allows you to get columns data that have utf8 (Unicode) flag.
=head1 SEE ALSO
L<Template::Stash::ForceUTF8>, L<DBIx::Class::UUIDColumns>.
=head1 METHODS
=head2 utf8_columns
=cut
sub encode_columns {
my $self = shift;
if (@_) {
foreach my $col (@_) {
$self->throw_exception("column $col doesn't exist")
unless $self->has_column($col);
}
return $self->_encode_columns({map { $_ => 1 } @_});
} else {
return $self->_encode_columns;
}
}
=head1 EXTENDED METHODS
=head2 get_column
=cut
sub get_column {
my ($self, $column) = @_;
my $value = $self->next::method($column);
my $cols = $self->_encode_columns;
if ($cols and defined $value and $cols->{$column}) {
decode($self->in_encoding, $value) unless is_utf8($value);
}
$value;
}
=head2 get_columns
=cut
sub get_columns {
my $self = shift;
my %data = $self->next::method(@_);
foreach my $col (
grep { defined $data{$_} }
keys %{$self->_utf8_columns || {}}
)
{
decode($self->in_encoding, $value) unless is_utf8($value);
}
%data;
}
=head2 store_column
=cut
sub store_column {
my ($self, $column, $value) = @_;
my $cols = $self->_utf8_columns;
if ($cols and defined $value and $cols->{$column}) {
encode($self->out_encoding, $value) if is_utf8($value);
}
$self->next::method($column, $value);
}
=head1 AUTHOR
Daisuke Murase <typester@cpan.org>
=head1 COPYRIGHT
This program is free software; you can redistribute
it and/or modify it under the same terms as Perl itself.
The full text of the license can be found in the
LICENSE file included with this module.
=cut
1;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment