Skip to content

Commit

Permalink
fix: for tag not respecting Drop#valueOf(), fixes #515
Browse files Browse the repository at this point in the history
  • Loading branch information
harttle committed Jul 9, 2022
1 parent a19feea commit c3e51ca
Show file tree
Hide file tree
Showing 6 changed files with 15 additions and 18 deletions.
4 changes: 0 additions & 4 deletions src/drop/drop.ts
Original file line number Diff line number Diff line change
@@ -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
}
Expand Down
3 changes: 2 additions & 1 deletion src/util/collection.ts
Original file line number Diff line number Diff line change
@@ -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)
Expand Down
2 changes: 1 addition & 1 deletion src/util/underscore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
3 changes: 1 addition & 2 deletions test/integration/builtin/tags/for.ts
Original file line number Diff line number Diff line change
Expand Up @@ -324,8 +324,7 @@ describe('tags/for', function () {
yield 'b'
yield 'c'
}

public valueOf (): string {
toString () {
return 'MockIterableDrop'
}
}
Expand Down
11 changes: 11 additions & 0 deletions test/integration/drop/drop.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 changes: 0 additions & 10 deletions test/unit/drop/drop.ts

This file was deleted.

0 comments on commit c3e51ca

Please sign in to comment.