Skip to content

Instantly share code, notes, and snippets.

@dajester2013
Last active April 28, 2020 21:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dajester2013/3133fdd1bd7e8e0f861a to your computer and use it in GitHub Desktop.
Save dajester2013/3133fdd1bd7e8e0f861a to your computer and use it in GitHub Desktop.
/**
* Color.cfc
*/
component extends=Enum {
static {
public final RED = enum("RED", [255,0,0]);
public final GREEN = enum("GREEN", [0,255,0]);
public final BLUE = enum("BLUE", [0,0,255]);
}
variables.r = 0;
variables.g = 0;
variables.b = 0;
private final function Color(r,g,b) {
structAppend(variables,arguments);
}
public string function toCssHex() {
return right("0" & InputBaseN(r, "16"), 2)
& right("0" & InputBaseN(g, "16"), 2)
& right("0" & InputBaseN(b, "16"), 2)
;
}
public string function toCssRGB() {
return "rgb(#r#, #g#, #b#)";
}
public string function toCssRGBA(required numeric a) {
return "rgba(#r#, #g#, #b#, #a % 256#)";
}
}
/**
* Provides helper methods for defining enum componentes.
*/
component {
// ######## STATIC ########
/**
* Create an enum value.
**/
private static function enum(required string name, args=[]) {
if (!structKeyExists(static,"__ET")) {
// Enum Type Name
static.__ET = rereplace(getcurrenttemplatepath(), ".+[\\/]([A-Za-z0-9]+)\.(cfc|lucee)", "\1");
// Enum Values
static.__EV = [];
}
if (!structKeyExists(static, name)) {
var inst = new "#static.__ET#"(name,args);
static.__EV.append(inst);
return inst;
} else {
return static[name];
}
}
/**
* Get enum values as an array
**/
public static function values() {
return duplicate(static.__EV);
}
/**
* Get the value of an enum
**/
public static function valueOf(required string name) {
return static[name];
}
// ######## INSTANCE ########
variables.__name = null;
variables.__ordinal = null;
private final function init(required string name, args=[]) {
variables.__name = name;
variables.__ordinal = static.__EV.len();
if (structKeyExists(this,static.__ET)) {
if (!structKeyExists(static,"__ECP")) {
var md = getMetaData(this[static.__ET]);
static.__ECP = md.access == "private" && md.modifier == "final";
}
if (static.__ECP) {
this[static.__ET](argumentCollection=args);
} else {
throw(message="Enum constructor must be marked 'private final'.");
}
}
}
public final function name() {
return variables.__name;
}
public final function ordinal() {
return variables.__ordinal;
}
public final function __toString() {
return name();
}
}
<cfoutput>
<style>
.warning {
background: #Color::RED.toCssRGB()#
}
.success {
background: #Color::GREEN.toCssRGB()#
}
</style>
</cfoutput>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment