Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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