Subject: | Add helper functions to enforce certain types. |
Hi, sometimes there are circumstances where the auto-detection of
string/int does not work or the server is e.g. expecting a number
as a string.
This issue is discussed here:
http://www.perlmonks.org/index.pl?node_id=920054
I suggest to extend XML/RPC.pm with the following helper functions:
(just copy/paste them before the final '1;'):
Thanks
Perlbotics
#--- Helper functions
# Inspired by: http://www.perlmonks.org/?node_id=920054
# Example: $xmlrpc->call( 'some_meth', { some_param => XML::RPC::string(
12345 ) } );
#
# TODO: add checks (e.g. double: is double or croak())?
# TODO: usefull auto-conversion (int: int(shift)?)
# TODO: add t/testcases*.t
# TODO: add member-functions? e.g. $xmlrpc->string( 12345 ) (IMHO, no
good idea.)
use MIME::Base64;
use Time::Local;
# cosmetics: member-function to set xml_out indentation (call before
XML::RPC::call(...))
sub indent {
my $self = shift || return;
$self->{tpp}->set( indent => shift );
}
# private helper function to create specialised closure
sub _cast {
my ($type, $val) = @_;
return sub { return { "$type" => $val }; };
}
sub string { return _cast( 'string', shift ); }
sub int { return _cast( 'int', int shift ); }
sub i4 { return _cast( 'i4', int shift ); }
sub double { return _cast( 'double', sprintf('%g', shift) ); }
sub boolean { return _cast( 'boolean', (shift) ? '1' : '0' ); }
sub base64 { chomp( my $base64 = encode_base64( shift ) );
return _cast( 'base64', $base64 );
}
# converts epoch (or current time if undef) to dateTime.iso8601 (UTC)
sub dateTime_iso8601 {
my $epoch = shift;
$epoch = time() unless defined $epoch; # could be: "shift // time"
with modern perl versions
my ($sec, $min, $hour, $mday, $mon, $year, $wday, $yday, $isdst) =
gmtime( $epoch );
return _cast( 'dateTime.iso8601',
sprintf('%4d%02d%02dT%02d:%02d:%02dZ',
$year + 1900, $mon + 1, $mday, $hour, $min, $sec)
);
}
#---
1;