fix: for tag not respecting Drop#valueOf(), fixes #515

This commit is contained in:
Harttle
2022-07-09 22:21:51 +08:00
parent a19feea7c4
commit c3e51caa70
6 changed files with 15 additions and 18 deletions
-4
View File
@@ -1,8 +1,4 @@
export abstract class Drop {
public valueOf (): any {
return undefined
}
public liquidMethodMissing (key: string | number): Promise<string | undefined> | string | undefined {
return undefined
}
+2 -1
View File
@@ -1,6 +1,7 @@
import { isNil, isString, isObject, isArray, isIterable } from './underscore'
import { isNil, isString, isObject, isArray, isIterable, toValue } from './underscore'
export function toEnumerable (val: any) {
val = toValue(val)
if (isArray(val)) return val
if (isString(val) && val.length > 0) return [val]
if (isIterable(val)) return Array.from(val)
+1 -1
View File
@@ -39,7 +39,7 @@ export function stringify (value: any): string {
}
export function toValue (value: any): any {
return value instanceof Drop ? value.valueOf() : value
return (value instanceof Drop && isFunction(value.valueOf)) ? value.valueOf() : value
}
export function isNumber (value: any): value is number {
+1 -2
View File
@@ -324,8 +324,7 @@ describe('tags/for', function () {
yield 'b'
yield 'c'
}
public valueOf (): string {
toString () {
return 'MockIterableDrop'
}
}
+11
View File
@@ -61,4 +61,15 @@ describe('drop/drop', function () {
const html = await liquid.parseAndRender(`{{obj.foo}}`, { obj: new PromiseDrop() })
expect(html).to.equal('FOO')
})
it('should respect valueOf', async () => {
class CustomDrop extends Drop {
prop = 'not enumerable'
valueOf () {
return ['foo', 'bar']
}
}
const tpl = '{{drop}}: {% for field in drop %}{{ field }};{% endfor %}'
const html = await liquid.parseAndRender(tpl, { drop: new CustomDrop() })
expect(html).to.equal('foobar: foo;bar;')
})
})
-10
View File
@@ -1,10 +0,0 @@
import { expect } from 'chai'
import { Drop } from '../../../src/drop/drop'
describe('drop/drop', function () {
class CustomDrop extends Drop { }
it('.valueOf() should return undefined by default', async function () {
expect(new CustomDrop().valueOf()).to.be.undefined
})
})