Skip to content

Commit

Permalink
Fix IDictionary implementation for ScriptObject
Browse files Browse the repository at this point in the history
  • Loading branch information
xoofx committed May 1, 2023
1 parent 3912f57 commit 003e1ac
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 4 deletions.
11 changes: 10 additions & 1 deletion src/Scriban.Tests/TestRuntime.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@
// Licensed under the BSD-Clause 2 license. See license.txt file in the project root for full license information.

using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Numerics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using Newtonsoft.Json;
using NUnit.Framework;
Expand All @@ -24,6 +24,15 @@ namespace Scriban.Tests
[TestFixture]
public class TestRuntime
{
[Test]
public void TestScriptObjectAsDictionary()
{
var model = (IDictionary)(new ScriptObject());
model.Add("name", "John");
model.Add("age", 20);
Assert.AreEqual("John", model["name"]);
Assert.AreEqual(20, model["age"]);
}

[Test]
public void TestLazy()
Expand Down
23 changes: 20 additions & 3 deletions src/Scriban/Runtime/ScriptObject.cs
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,8 @@ public ScriptObject(int capacity, bool? autoImportStaticsFromThisType, IEquality

void IDictionary.Add(object key, object value)
{
((IDictionary) Store).Add(key, value);
this.AssertNotReadOnly();
Store.Add((string) key, new InternalValue(value));
}

/// <summary>
Expand Down Expand Up @@ -144,8 +145,24 @@ object ICollection.SyncRoot

object IDictionary.this[object key]
{
get { return ((IDictionary) Store)[key]; }
set { ((IDictionary) Store)[key] = value; }
get
{
var str = key as string ?? key.ToString();
return Store[str].Value;
}
set
{
this.AssertNotReadOnly();
var str = key as string ?? key.ToString();
if (Store.TryGetValue(str, out var previousValue))
{
Store[str] = new InternalValue(value, previousValue.IsReadOnly);
}
else
{
Store[str] = new InternalValue(value);
}
}
}

public IEnumerable<string> GetMembers()
Expand Down

0 comments on commit 003e1ac

Please sign in to comment.