public
Created

ResourceStringUtil

  • Download Gist
ResourceStringUtil.as
ActionScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
package com.mimswright.flex.utils
{
import mx.resources.ResourceManager;
/**
* A utility for string related functions within.
*
* @author Mims H. Wright
*/
public class ResourceStringUtil
{
public static function get DEFAULT_BUNDLE():String { return "Strings"; }
/**
* Replaces tokens in a resource string with values from a generic object.
* The tokens in the string will be replaced if a matching named property exists
* in the tokenValues object.
*
* @param key The key name for looking up the string in the resource bundle.
* @param tokenValues A generic object containing values for the tokens.
* @param bundle The resource bundle to use. Default is Strings.
*
* @example <listing version="3.0">
*
* // If the following is defined in Strings.properties...
* userSelectedProductMessage=%userName% viewed %productName% at %date%.
*
* // you could retrieve that data with values replaced by using...
* var message:String = PurchliveStringUtil.getResoureceStringWithTokens(
* "userSelectedProductMessage",
* {
* userName: "mims",
* productName: product.name,
* date: newDate()
* });
*/
static public function getResourceStringWithTokens(key:String, tokenValues:Object, bundle:String = ""):String {
if (bundle == "") { bundle = DEFAULT_BUNDLE; }
var string:String = ResourceManager.getInstance().getString(bundle, key);
// match tokens in the format %token%
var tokens:Array = string.match(/%[A-Za-z0-9]+%/g);
for each (var token:String in tokens) {
var propertyName:String = token.slice(1, token.length-1);
if (tokenValues[propertyName] != undefined && tokenValues[propertyName] != null) {
var value:String = String(tokenValues[propertyName]);
string = string.replace("%" + propertyName + "%", value);
} else {
//else just make that string blank.
string = string.replace("%" + propertyName + "%", "");
}
}
return string;
}
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.