Created
May 23, 2012 06:38
-
-
Save ballpointcarrot/2773569 to your computer and use it in GitHub Desktop.
Generic substitution with Procs
This file contains 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 Content | |
MATCHERS = [{:regex => /\[Contact\]/i, :proc => Proc.new{|options| options[:contact].name}}, | |
{:regex => /\[Site\]/i, :proc => Proc.new{|options| options[:site].name}}] | |
attr_accessor :body | |
def prepare_form_letter(contact, site) | |
parsed = self.body | |
MATCHERS.each do |matcher| | |
parsed.gsub!(matcher[:regex], matcher[:proc].call({:contact => contact, :site => site})) | |
end | |
parsed | |
end | |
end | |
class Contact | |
attr_accessor :name | |
end | |
class Site | |
attr_accessor :name | |
end | |
### Runtime ### | |
c = Contact.new | |
c.name = "Hello" | |
s = Site.new | |
s.name = "World!" | |
con = Content.new | |
con.body = "Dear [Contact],..." #All of the form letter above | |
con.prepare_form_letter(c,s) # Outputs form letter, with names replaced in the content. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment