Skip to content

Commit

Permalink
invoke methods
Browse files Browse the repository at this point in the history
  • Loading branch information
davidchambers committed Apr 16, 2012
1 parent 78b5e60 commit 0c2ed5d
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
13 changes: 13 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`:
Expand Down
6 changes: 6 additions & 0 deletions spec/stringformat_spec.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -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', ->
Expand Down
3 changes: 2 additions & 1 deletion string-format.coffee
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {}

Expand Down

0 comments on commit 0c2ed5d

Please sign in to comment.