简体   繁体   中英

Using gsub only when the string is included in the text

The app that I'm building allows users to store first and last names of contacts. First names are mandatory, but, last names aren't. In some cases they exist and in some cases they don't.

I tried using the following logic to replace FNAME and LNAME in the mailer. I had to use this in the mailer because the logic for sending the group mail gives me no room elsewhere.

message = @mailer.message.gsub! 'FNAME', contact.first_name if @mailer.message includes? ('FNAME')
@body = message.gsub! 'LNAME', contact.last_name || '' if message includes?('LNAME')

This throws an undefined method includes?' with error class NoMethodError`. Ideally I would like to ignore gsub! if there is no LNAME or FNAME in the message.

There is a missing dot before the #includes? method call:

message = @mailer.message.gsub! 'FNAME', contact.first_name if @mailer.message.includes?('FNAME')

But you don't need to check the existence of the substring with #includes? #gsub! will only replace the content if there is a match, so:

message = @mailer.message.gsub!('FNAME', contact.first_name)

Is enough, if @mailer.message could be nil , then a further check is needed:

message = @mailer.message.gsub!('FNAME', contact.first_name) if @mailer.message.present?

And BTW #gsub! will modify the original string, so you probably what you really wanted to write is:

if @mailer.message.present?
  @mailer.message.gsub!('FNAME', contact.first_name)
  @mailer.message.gsub!('LNAME', contact.last_name)
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM