Created
May 5, 2010 08:26
-
-
Save choonkeat/390534 to your computer and use it in GitHub Desktop.
Sometimes you just need objects that spew placeholder strings
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # Sometimes you just need objects that spew placeholder strings | |
| # | |
| # Regular supplant style http://javascript.crockford.com/remedial.html | |
| # >> x = SupplantTemplate.new | |
| # => "" | |
| # >> x.client.company_name | |
| # => "{client_company_name}" | |
| # >> x.client | |
| # => "{client}" | |
| # >> x.id | |
| # => "{id}" | |
| # >> x.description | |
| # => "{description}" | |
| # | |
| # or Mustache style http://mustache.github.com/ | |
| # >> x = SupplantTemplate.new('', '{{', '}}') | |
| # => "" | |
| # >> x.client.company_name | |
| # => "{{client_company_name}}" | |
| # >> x.client | |
| # => "{{client}}" | |
| # >> x.id | |
| # => "{{id}}" | |
| # | |
| class SupplantTemplate < String | |
| def initialize(string = '', lquo = '{', rquo = '}') | |
| @lquo = lquo | |
| @rquo = rquo | |
| super(string) | |
| end | |
| def id | |
| method_missing(:id) | |
| end | |
| def method_missing(symbol, *args) | |
| parts = (self == '' ? [symbol] : [self.gsub(@lquo, '').gsub(@rquo, ''), symbol]) | |
| self.class.new("#{@lquo}#{parts.join('_')}#{@rquo}", @lquo, @rquo) | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment