feat(Drop): liquid_method_missing and to_s

close #97
This commit is contained in:
harttle
2019-01-28 19:53:04 +08:00
parent f38ea63c14
commit 4dffb27e95
5 changed files with 57 additions and 25 deletions
+20 -10
View File
@@ -60,16 +60,10 @@ const Scope = {
if (_.isNil(obj)) {
val = undefined
} else {
if (typeof obj.to_liquid === 'function') {
obj = obj.to_liquid()
} else if (typeof obj.toLiquid === 'function') {
obj = obj.toLiquid()
}
if (key === 'size' && (_.isArray(obj) || _.isString(obj))) {
val = obj.length
} else {
val = obj[key]
obj = toLiquid(obj)
val = key === 'size' ? readSize(obj) : obj[key]
if (_.isFunction(obj.liquid_method_missing)) {
val = obj.liquid_method_missing(key)
}
}
if (_.isNil(val) && this.opts.strict_variables) {
@@ -138,6 +132,22 @@ const Scope = {
}
}
function toLiquid (obj) {
if (_.isFunction(obj.to_liquid)) {
return obj.to_liquid()
}
if (_.isFunction(obj.toLiquid)) {
return obj.toLiquid()
}
return obj
}
function readSize (obj) {
if (!_.isNil(obj.size)) return obj.size
if (_.isArray(obj) || _.isString(obj)) return obj.length
return obj.size
}
function matchRightBracket (str, begin) {
let stack = 1 // count of '[' - count of ']'
for (let i = begin; i < str.length; i++) {
+14 -12
View File
@@ -1,4 +1,5 @@
const toStr = Object.prototype.toString
const arrToStr = Array.prototype.toString
/*
* Checks if value is classified as a String primitive or object.
@@ -9,6 +10,10 @@ export function isString (value) {
return toStr.call(value) === '[object String]'
}
export function isFunction (value) {
return typeof value === 'function'
}
export function promisify (fn) {
return function () {
return new Promise((resolve, reject) => {
@@ -20,19 +25,16 @@ export function promisify (fn) {
}
export function stringify (value) {
if (isNil(value)) {
return String(value)
}
if (typeof value.to_liquid === 'function') {
return stringify(value.to_liquid())
}
if (typeof value.toLiquid === 'function') {
return stringify(value.toLiquid())
}
if (isString(value) || value instanceof RegExp || value instanceof Date) {
return value.toString()
}
if (isNil(value)) return String(value)
if (isFunction(value.to_liquid)) return stringify(value.to_liquid())
if (isFunction(value.toLiquid)) return stringify(value.toLiquid())
if (isFunction(value.to_s)) return value.to_s()
if ([toStr, arrToStr].indexOf(value.toString) > -1) return defaultToString(value)
if (isFunction(value.toString)) return value.toString()
return toStr.call(value)
}
function defaultToString (value) {
const cache = []
return JSON.stringify(value, (key, value) => {
if (isObject(value)) {