Commits

David Chambers committed 1d8efb6

invoke methods

Comments (0)

Files changed (4)

     "{owner}/{slug} has {followers.length} followers".format(repo)
     # "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`:

spec/stringformat_spec.coffee

     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', ->

string-format.coffee

   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 = {}
   };
 
   lookup = function(object, key) {
-    var match;
+    var match, value;
     if (!/^(\d+)([.]|$)/.test(key)) {
       key = '0.' + key;
     }
       object = object[match[1]];
       key = match[2];
     }
-    return object[key];
+    value = object[key];
+    if (typeof value === 'function') {
+      return value.call(object);
+    } else {
+      return value;
+    }
   };
 
   format.transformers = {};
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.