Skip to content

Instantly share code, notes, and snippets.

@jacoby
Last active January 30, 2017 01:37
Show Gist options
  • Save jacoby/5319959 to your computer and use it in GitHub Desktop.
Save jacoby/5319959 to your computer and use it in GitHub Desktop.
Perl Module to handle export of hashrefs based upon requested format.
package API ;
use 5.010 ;
use strict ;
use warnings ;
use CGI ;
use Exporter 'import' ;
use Data::Dumper ;
use JSON ;
use YAML ;
our @EXPORT ;
our @EXPORT_OK ;
our %EXPORT_TAGS ;
BEGIN {
our @EXPORT = qw{
export_determined
} ;
}
sub export_determined {
my ( $ref , $cgi , $disposition) = @_ ;
my $path_info = $cgi->path_info ;
my @path_info = split m{/} , $path_info ;
if ( lc $path_info[1] eq 'yaml' ) {
say 'content-type: application/x-yaml' ;
say join '' ,
'content-disposition: attachment;filename=' ,
$disposition ,
'.yaml' if $disposition ;
say '' ;
print Dump( $ref ) ;
}
elsif ( lc $path_info[1] eq 'csv' ) {
say 'content-type: application/csv' ;
say join '' ,
'content-disposition: attachment;filename=' ,
$disposition ,
'.csv' if $disposition ;
say '' ;
if ( ref $ref eq 'ARRAY' ) {
for my $line ( @$ref ) {
say join ',' , @$line ;
}
return ;
}
if ( ref $ref eq 'HASH' ) {
my ( $k ) = keys %$ref ;
my $key = $ref->{ $k } ;
my @headers = keys %$key ;
say join ',' , @headers ;
for my $k ( sort keys %$ref ) {
say join ',' ,
map {
$ref->{ $k }->{ $_ } || ''
}
@headers ;
}
return ;
}
}
elsif ( lc $path_info[1] eq 'xml' ) {
say 'content-type: application/xml' ;
say join '' ,
'content-disposition: attachment;filename=' ,
$disposition ,
'.xml' if $disposition ;
say '' ;
print 'undef' ;
}
elsif ( lc $path_info[1] eq 'dump' ) {
say 'content-type: text/plain' ;
say join '' ,
'content-disposition: attachment;filename=' ,
$disposition ,
'.txt' if $disposition ;
say '' ;
print Dumper $ref ;
}
else {
# json
say 'content-type: application/json' ;
say join '' ,
'content-disposition: attachment;filename=' ,
$disposition ,
'.json' if $disposition ;
say '' ;
print encode_json $ref ;
}
}
'version 1' ;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment