Any-Renderer

 view release on metacpan or  search on metacpan

lib/Any/Renderer/Data/Serializer.pm  view on Meta::CPAN

  
  unless($Formats{$format}) {
    _scan_available_formats(); #Discover if it's appeared recently
    die("The format '$format' doesn't appear to be supported by Data::Serializer") unless($Formats{$format});
  }
  
  my $self = {
    'format'  => $format,
    'options' => $options,
  };

  bless $self, $class;
  return $self;
}

sub render
{
  my ( $self, $data ) = @_;

  TRACE ( "Rendering w/Data::Serializer" );
  DUMP ("Input data structure", $data );

  my $ds = new Data::Serializer('serializer' => $self->{format}, 'options' => $self->{options}) or die($!);
  my $string = $ds->raw_serialize($data);
  TRACE("Rendered as: " . $string);
  return $string;
}

sub requires_template
{
  my ( $format ) = @_;
  return 0; #None do
}

sub available_formats
{
  _scan_available_formats();
  return [ sort keys %Formats ];
}


sub _scan_available_formats
{
  TRACE ( "Generating list of all possible formats" );

  my @possible_locations = grep { -d $_ } map { File::Spec->catdir ( $_, split ( /::/, 'Data::Serializer' ) ) } @INC;

  my %found;
  my $collector = sub
  {
    return unless $_ =~ /\.pm$/;

    my $file = $File::Find::name;
    $file =~ s/\Q$File::Find::topdir\E//;
    $file =~ s/\.pm$//;

    my @dirs = File::Spec->splitdir ( $file );
    shift @dirs;
    $file = join ( "::", @dirs );

    return if $file eq 'Cookbook'; #Skip non-backend modules in D::S namespace

    $found{ $file } = 1;
  };

  File::Find::find ( $collector, @possible_locations );
  
  #Only add those that compile
  if(MUST_COMPILE) {
    %Formats = ();
    foreach my $module (keys %found) {
      eval {
        _load_module($module);
        $Formats{$module} = 1;
      };
      warn($@) if($@);
    }
  } else {
    %Formats = %found;  
  }
  
  DUMP("Available formats", \%Formats);
}

sub _load_module {
  my $file = shift; 

  my $module = "Data::Serializer::" . $file;  
  TRACE ( "Loading Data::Serializer backend '" . $module . "'" );
  die ("Module name $module looks dodgy - will not load") unless($module =~ /^[\w:]+$/); #Protect against code injection
  eval "require " . $module;
  die ("Data::Serializer - problem loading backend module: ". $@ ) if ( $@ );
  
  return $module;
}

sub TRACE {}
sub DUMP {}

1;

=head1 NAME

Any::Renderer::Data::Serializer - adaptor for Any::Renderer to use any Data::Serializer backends

=head1 SYNOPSIS

  use Any::Renderer;

  my %options = ();
  my $format = "YAML"; #One of the formats provided by Data::Serializer
  my $r = new Any::Renderer ( $format, \%options );

  my $data_structure = [...]; # arbitrary structure code
  my $string = $r->render ( $data_structure );

=head1 DESCRIPTION

Any::Renderer::Data::Serializer renders any Perl data structure passed to it into
a string representation using modules exposing the Data::Serializer API.



( run in 2.336 seconds using v1.01-cache-2.11-cpan-5b529ec07f3 )