diff --git a/README.md b/README.md index 5421985..a9df66f 100644 --- a/README.md +++ b/README.md @@ -70,6 +70,19 @@ repo = owner: "pypy", slug: "pypy", followers: [...] # "pypy/pypy has 516 followers" ``` +If the referenced property is a method, it is invoked and the result is used +as the replacement string: + +```coffeescript +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" +``` + ### String.prototype.format.transformers “Transformers” can be attached to `String.prototype.format.transformers`: diff --git a/spec/stringformat_spec.coffee b/spec/stringformat_spec.coffee index dc14d8f..c9e4757 100644 --- a/spec/stringformat_spec.coffee +++ b/spec/stringformat_spec.coffee @@ -47,6 +47,12 @@ describe 'String::format', -> bobby = first_name: 'Bobby', last_name: 'Fischer' '{first_name} {last_name}'.format(bobby).should_be 'Bobby Fischer' + it 'invokes methods', -> + '{0.toLowerCase}'.format('III').should_be 'iii' + '{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' + String::format.transformers.s = -> 's' unless +this is 1 it 'applies transformers to explicit positional arguments', -> diff --git a/string-format.coffee b/string-format.coffee index d9af851..d56a800 100644 --- a/string-format.coffee +++ b/string-format.coffee @@ -31,7 +31,8 @@ lookup = (object, key) -> while match = /(.+?)[.](.+)/.exec key object = object[match[1]] key = match[2] - object[key] + value = object[key] + if typeof value is 'function' then value.call object else value format.transformers = {}