Skip to content

Instantly share code, notes, and snippets.

@ballpointcarrot
Created May 23, 2012 06:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ballpointcarrot/2773569 to your computer and use it in GitHub Desktop.
Save ballpointcarrot/2773569 to your computer and use it in GitHub Desktop.
Generic substitution with Procs
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