Permalink
Browse files

Added dynamic object finding functionality for merging. ( ::[user-1].…

…name:: -> User.find(1).name )
  • Loading branch information...
1 parent d7a1f4c commit b636066824d8e0110eeba9a4533ccb03b6d189f7 @ehlertij committed Jul 13, 2011
Showing with 31 additions and 5 deletions.
  1. +7 −1 README.rdoc
  2. +24 −4 lib/mail_merge.rb
View
@@ -5,9 +5,15 @@ Mail Merge Gem
Parses a string and replaces specified merge fields with the evaluated result:
[Usage]
-* MailMerge.merge(content, options = {}, merge_fields = [], delimeter = "::")
+* MailMerge.merge(content, options = {}, merge_fields = [], delimeter = "::", allow_dynamic = false)
[Examples]
+* content = "Welcome to ::site.name::, ::user.full_name::!"
* merged_content = MailMerge.merge(content, {:site => @site, :user => @user}, ['::site.name::', '::user.full_name::']) # Basic example
* merged_content = MailMerge.merge(content, {:site => @site, :user => @user}) # This will evaluate any merge fields that start with 'site' or 'user'
* merged_content = MailMerge.merge(content, {:site => @site, :user => @user}, ['~~site.name~~', '~~user.full_name~~'], "~~") # Using your own delimeter
+
+
+* content = "Welcome, ::[user-1].full_name::!"
+ merged_content = MailMerge.merge(:content => content, :allow_dynamic => true) # This will call find on any fields wrapped in [] (Ex. User.find(1).full_name)
+ # output: "Welcome, Andrew Wiggin!"
View
@@ -4,16 +4,16 @@ module MailMerge
# will search text_block.content and find all instances of ::user.[method]::
# and ::site.[method]:: and send the [method] to the associated object
# Chaining works as well (ex. ::site.organization.name:: yields 'TST Media')
- def self.merge(content, options = {}, merge_fields = [], delimeter = "::")
+ # Supports finding of objects with this syntax: ::[user-1].full_name:: (calls User.find(1).full_name)
+ # - requires allow_dynamic flag to be true
+ def self.merge(content, options = {}, merge_fields = [], delimeter = "::", allow_dynamic = false)
merged = content
options.keys.each do |key|
obj = options[key]
merged = merged.gsub(/#{delimeter}#{key.to_s}\.[\w|\.]*#{delimeter}/) do |s|
if merge_fields.empty? or merge_fields.include?(s)
begin
- res = s[/\..*\w/][/\w.*/].split('.').collect{|m| obj = obj.send(m)}.last
- obj = options[key]
- res
+ call_methods(s, obj)
rescue
s
end
@@ -22,7 +22,27 @@ def self.merge(content, options = {}, merge_fields = [], delimeter = "::")
end
end
end
+ if allow_dynamic
+ objects = {}
+ merged = merged.gsub(/#{delimeter}\[?\w*(-\d*)?\]?\.[\w|\.]*#{delimeter}/) do |s|
+ x = s[/\[?\w*-\d*\]/].delete('[]')
+ begin
+ unless objects[x]
+ class_name, id = x.split('-')
+ objects[x] = class_name.camelize.constantize.find(id)
+ end
+ call_methods(s, objects[x])
+ rescue
+ s
+ end
+ end
+ end
merged
end
+ private
+ def self.call_methods(s, obj)
+ s[/\..*\w/][/\w.*/].split('.').collect{|m| obj = obj.send(m)}.last
+ end
+
end

0 comments on commit b636066

Please sign in to comment.