Skip to content

Instantly share code, notes, and snippets.

@kthompson
Created February 22, 2011 22:39
Show Gist options
  • Save kthompson/839590 to your computer and use it in GitHub Desktop.
Save kthompson/839590 to your computer and use it in GitHub Desktop.
Simple Ruby-esque option/hash value passing.
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);
}
}
// 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();
}
@sekhat
Copy link

sekhat commented Feb 23, 2011

That's pretty clever. Yet simple. I like it :) I'll have to remember this ^_^

You should send this to ASP.NET MVC team. It will make writing the option things they have where they use anonymous types much nicer to read :D

@kthompson
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment