Created
December 17, 2015 23:58
-
-
Save LinuxDoku/c1b2e68d28b6745da476 to your computer and use it in GitHub Desktop.
Null check the model when working with nancy's super simple view engine.
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
using System.Text.RegularExpressions; | |
using Nancy.ViewEngines.SuperSimpleViewEngine; | |
namespace Residata.Analysis.Web.Infrastructure { | |
/// <summary> | |
/// Null Check Matcher for the super simple view engine. | |
/// | |
/// This checks if the model is null - or not! | |
/// </summary> | |
/// <example> | |
/// @IsNull | |
/// Ops, could not find the requested object :-( | |
/// @EndIsNull | |
/// | |
/// @IsNotNull | |
/// Found it :-) | |
/// @EndIsNull | |
/// </example> | |
public class NullCheckMatcher : ISuperSimpleViewEngineMatcher { | |
private static readonly Regex NullCheckRegEx = new Regex(@"@(?<Type>IsNull|IsNotNull);?(?<Contents>.*?)@EndIsNull;?", RegexOptions.Singleline | RegexOptions.Compiled); | |
public string Invoke(string content, dynamic model, IViewEngineHost host) { | |
return NullCheckRegEx.Replace(content, x => { | |
var type = x.Groups["Type"].Value; | |
var contents = x.Groups["Contents"].Value; | |
if (type == "IsNull") { | |
if (model == null) { | |
return contents; | |
} | |
} | |
else if (type == "IsNotNull") { | |
if (model != null) { | |
return contents; | |
} | |
} | |
return string.Empty; | |
}); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment