Skip to content

Commit

Permalink
Nullable values need to be converted to null safely (#136)
Browse files Browse the repository at this point in the history
Not sure how this originally worked but since the changes for save access this is broken because types don't match
  • Loading branch information
Romanx authored Sep 23, 2022
1 parent eec4032 commit 7e5bab6
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 7 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -40,13 +40,22 @@ protected override void Write(CompilationRenderer renderer, InterpolationToken o
var formattedToString = expression.Type
.GetMethod(nameof(object.ToString), formatProviderTypeArgs);

var item = expression.Type.IsNullable()
? Expression.Coalesce(expression, Expression.Constant(string.Empty))
: expression;
var toString = formattedToString is not null
? Expression.Call(expression, formattedToString, Expression.Constant(context.CompilationSettings.CultureInfo))
: Expression.Call(expression, expression.Type.GetMethod(nameof(object.ToString), Type.EmptyTypes));

stringExpression = formattedToString is object
? Expression.Call(item, formattedToString, Expression.Constant(context.CompilationSettings.CultureInfo))
: Expression.Call(item, expression.Type.GetMethod(nameof(object.ToString), Type.EmptyTypes));
var item = expression;
if (expression.Type.IsNullable())
{
stringExpression = Expression.Condition(
Expression.Equal(expression, Expression.Default(expression.Type)),
Expression.Default(typeof(string)),
toString);
}
else
{
stringExpression = toString;
}
}

expression = Expression.Invoke(context.CompilerSettings.EncodingFuction, stringExpression);
Expand Down
9 changes: 9 additions & 0 deletions test/Stubble.Compilation.Tests/RenderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -531,13 +531,22 @@ public void It_Should_Throw_Exception_On_Dynamic_IgnoreCase()
Partials = new Dictionary<string, string>
{
}
},
new SpecTest
{
Name = "A model with a nullable int",
Data = new ExampleClass { Count = 3 },
Template = "{{Count}}",
Expected = "3"
}
}.Select(s => new[] { s });

private class ExampleClass
{
public string Foo { get; set; }

public int? Count { get; set; }

public string MethodWithDefault(string value = "Foobar") => value;

public static string StaticMethodWithDefault(string value = "Static-Foobar") => value;
Expand Down
2 changes: 1 addition & 1 deletion test/Stubble.Test.Shared/Spec/SpecTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public class SpecTest

public bool Skip { get; set; }

public IDictionary<string, string> Partials { get; set; }
public IDictionary<string, string> Partials { get; set; } = new Dictionary<string, string>();

public Exception ExpectedException { get; set; }

Expand Down

0 comments on commit 7e5bab6

Please sign in to comment.