Created
February 22, 2011 22:39
-
-
Save kthompson/839590 to your computer and use it in GitHub Desktop.
Simple Ruby-esque option/hash value passing.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Option | |
{ | |
public string Name { get; private set; } | |
public string Value { get; private set; } | |
private Option(Expression<Func<string, string>> action) | |
{ | |
this.Name = ToCommand(action.Parameters[0].Name); | |
if (this.Name == "klass") | |
this.Name = "class"; | |
this.Value = action.Compile()(null); | |
} | |
private static string ToCommand(string name) | |
{ | |
return new Regex("[a-z][A-Z]").Replace(name, match => match.Value.Substring(0,1) + "-" + match.Value.Substring(1,1).ToLower()); | |
} | |
public static implicit operator Option(Expression<Func<string, string>> action) | |
{ | |
return new Option(action); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// WriteTag("script", script => { }, text => "text/javascript", id => "script_id"); | |
public void WriteTag(string tagName, Action<HtmlReportWriter> contents = null, params Expression<Func<string, string>>[] attributes) | |
{ | |
_writer.WriteStartElement(tagName); | |
foreach (Option attribute in attributes) | |
_writer.WriteAttributeString(attribute.Name, attribute.Value); | |
if (contents != null) | |
contents(this); | |
_writer.WriteEndElement(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks. A word of warning... this technique should only be used with simple types/values i.e. no actual functions for options as the code generated for it may have some major performance issues.