Created
October 10, 2014 10:55
-
-
Save mikebaldry/556c21579f48076b3b1e to your computer and use it in GitHub Desktop.
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
class Template | |
def initialize(content) | |
@content = content | |
end | |
def render(context) | |
context = Hashie::Mash.new(context) | |
@content.gsub(/(%{([^}]+)})/) do | |
context[Regexp.last_match[2]] | |
end | |
end | |
end |
Thanks
Talking of the regex stuff, you can visualise regular expressions with rubular
http://www.rubular.com/r/YLwi7xPkZP
so you see each match matches 2 things, the whole text (%{blah}) and the just key (blah) which is what I wanted.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@context
is aHash
of some description, so you can doso
String#gsub
replaces things with other things, it takes strings or regular expressions, if you pass 2 parameters, it'll replace every match of the first parameter, with the second parameter. If you pass it 1 parameter and a block, it'll execute the block for every match, and use the return value of the block as what to replace with.the block takes 1 parameter, which is the whole match (e.g.
"%{blah}"
) but I wanted the third match, which you can't access directly as the list of matches from the regular expression isn't passed to the block (for some reason). So you can use the perl syntax$0
$1
$2
to get the matches, or useRegexp.last_match[x]
which looks a bit nicer.