I have several controllers that take an instance of different classes each (Email, Call, Letter, etc) and they all have to go through this same substitution:
@email.message.gsub!("{FirstName}", @contact.first_name)
@email.message.gsub!("{Company}", @contact.company_name)
@email.message.gsub!("{Colleagues}", @colleagues.to_sentence)
@email.message.gsub!("{NextWeek}", (Date.today + 7.days).strftime("%A, %B %d"))
@email.message.gsub!("{ContactTitle}", @contact.title )
So, for example, @call.message for Call, @letter.message for Letter, etcetera.
This isn’t very dry. I tried the following:
class ApplicationController < ActionController::Base
helper :all # include all helpers, all the time
def message_sub(asset, contact, colleagues)
asset.message.gsub!("{FirstName}", contact.first_name)
asset.message.gsub!("{Company}", contact.company_name)
asset.message.gsub!("{Colleagues}", colleagues.to_sentence)
asset.message.gsub!("{NextWeek}", (Date.today + 7.days).strftime("%A, %B %d"))
asset.message.gsub!("{ContactTitle}", contact.title )
end
end
So in, say, the Letter Controller have this:
@letter = Letter.find(params[:letter]) #:letter was passed as a hash of the letter instance
message_sub(@letter, @contact, @colleagues)
@contact_letter.body = @letter.body
But the above doesn’t work.
To answer your question directly, you want a module. You can put it in your lib directory.
Then in your controller
However, as some have already pointed out, this is probably better at the model level:
Which you would then include at the model level, and then call in your controller like
@letter.substituted_message(@contact, @colleagues)However, I’m a little confused that what you posted didn’t work, though. If it’s defined on ApplicationController it should work. Module-based solution still better IMO.