Yes indeedy, YAML is fun. A project that I’ve been working on required that I set up a simple fault and tracking hook in the Flash application that then notified a bug tracking service, in this case it’s Hoptoad.
Apart from being a dyslexic’s nightmare to pronounce, it’s actually a really nice and simple service that keeps track of any faults that may appear in your code from time to time.
So back to YAML: Hoptoad has a nice service whereby you can post any errors to its API, the problem there is that those errors had to be posted in a YAML format, and I wasn’t coding in Ruby. So, I used my ingenuity and created a simple YAML helper:
{
import flash.utils.describeType;
public class YAMLUtil
{
public static function formatArray(array:Array, tab:String):String
{
var result:String = '';
for each ( var item:Object in array )
{
result += '\n' + tab + '- "' + item.toString() + '"';
}
return result;
}
public static function formatHash(hash:Object, tab:String, depth:Number=1):String
{
var hashInfo:XML = describeType( hash );
var result:String = '';
var item:*;
var itemInfo:XML;
if ( hashInfo.@name == 'Object' )
{
for ( var key:String in hash )
{
item = hash[ key ];
itemInfo = describeType( item );
result += '\n' + StringUtil.multiply( tab, depth ) + key +': ' + ( itemInfo.@name == 'String' ? item : '' ) + '';
if ( itemInfo.@name != 'String' )
{
result += formatHash( item, tab, depth + 1 );
}
}
}
else
{
for each ( var v:XML in hashInfo..*.( name() == 'variable' || name() == 'accessor' ) )
{
item = hash[ v.@name ];
result += '\n' + StringUtil.multiply( tab, depth ) + v.@name +': ' + item + '';
}
}
return result;
}
}
}
It’s all up on my github too, and it’s quite simple to use, for example:
{
var request:URLRequest = new URLRequest( vo.url );
var loader:URLLoader = new URLLoader();
request.method = URLRequestMethod.POST;
request.data = getYAMLData( text );
request.contentType = 'application/x-yaml';
if ( CurrentEnvironment.isProduction )
{
try
{
loader.load( request );
} catch (e:*)
{ }
}
vo.faults.push( text );
}
private function getYAMLData(text:String):String
{
var yamlData:String = 'notice: \n'
+ ' api_key: ' + vo.apiKey + '\n'
+ ' error_message: "' + text + '"\n'
+ ' backtrace: ' + YAMLUtil.formatArray( trackBacksArray, ' ' ) + '\n'
+ ' request: ' + YAMLUtil.formatHash( requestHash, ' ', 2 ) + '\n'
+ ' session: ' + YAMLUtil.formatHash( sessionHash, ' ', 2 ) + '\n'
+ ' environment: \n'
+ ' RAILS_ENV: production\n';
return yamlData;
}
So it’ll take an array or hash (object) and format it correctly for YAML. Enjoy and tell me what you think!