From e648f22b9ab776929c1c10dc0d365addbb164ce6 Mon Sep 17 00:00:00 2001 From: David Chambers Date: Tue, 17 Apr 2012 00:43:22 -0700 Subject: [PATCH] invoke methods at any depth --- README.md | 6 ++++-- spec/stringformat_spec.coffee | 1 + string-format.coffee | 5 ++++- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index a9df66f..167229d 100644 --- a/README.md +++ b/README.md @@ -79,8 +79,10 @@ me = name: "David", dob: new Date "26 Apr 1984" "{name} was born in {dob.getFullYear}".format(me) # "David was born in 1984" -"{pop}{pop}{pop}".format(["one", "two", "three"]) -# "threetwoone" +sheldon = quip: -> "Bazinga!" + +"I've always wanted to go to a goth club. {quip.toUpperCase}".format(sheldon) +# "I've always wanted to go to a goth club. BAZINGA!" ``` ### String.prototype.format.transformers diff --git a/spec/stringformat_spec.coffee b/spec/stringformat_spec.coffee index c9e4757..2b1b574 100644 --- a/spec/stringformat_spec.coffee +++ b/spec/stringformat_spec.coffee @@ -52,6 +52,7 @@ describe 'String::format', -> '{0.toUpperCase}'.format('iii').should_be 'III' '{0.getFullYear}'.format(new Date '26 Apr 1984').should_be '1984' '{pop}{pop}{pop}'.format(['one', 'two', 'three']).should_be 'threetwoone' + '{quip.toUpperCase}'.format(quip: -> 'Bazinga!').should_be 'BAZINGA!' String::format.transformers.s = -> 's' unless +this is 1 diff --git a/string-format.coffee b/string-format.coffee index d56a800..dae0466 100644 --- a/string-format.coffee +++ b/string-format.coffee @@ -29,8 +29,11 @@ lookup = (object, key) -> unless /^(\d+)([.]|$)/.test key key = '0.' + key while match = /(.+?)[.](.+)/.exec key - object = object[match[1]] + object = resolve object, match[1] key = match[2] + resolve object, key + +resolve = (object, key) -> value = object[key] if typeof value is 'function' then value.call object else value