Skip to content

Instantly share code, notes, and snippets.

@mikebaldry
Created October 10, 2014 10:55
Show Gist options
  • Save mikebaldry/556c21579f48076b3b1e to your computer and use it in GitHub Desktop.
Save mikebaldry/556c21579f48076b3b1e to your computer and use it in GitHub Desktop.
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
@mrageh
Copy link

mrageh commented Oct 10, 2014

What is @content an Array?

@mrageh
Copy link

mrageh commented Oct 10, 2014

What's happening in lines 9 - 10?

@mikebaldry
Copy link
Author

@context is a Hash of some description, so you can do

Template.new("This is %{thing} and he is %{other_thing}").render(
  thing: "Adam",
  other_thing: "Awesome"
)

so 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 use Regexp.last_match[x] which looks a bit nicer.

@mrageh
Copy link

mrageh commented Oct 10, 2014

Thanks

@mikebaldry
Copy link
Author

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