0

I'm trying to have it so that when my form is submitted, I do some gsub validation on the model level before it is saved to the database.

Here's my model code:

class Blast < ActiveRecord::Base
    before_save :inliner

    def inliner
        self.body.gsub!('class=\"wysiwyg-color-grey\"' => 'style="color: #A9A9A9;"',
                                     'class=\"wysiwyg-color-blue\"' => 'style="color: #333399;"',
                                     'class=\"wysiwyg-color-purple\"' => 'style="color: #663399;"',
                                     'class=\"wysiwyg-color-red\"' => 'style="color: #CC3333;"',
                                     'class=\"wysiwyg-color-orange\"' => 'style="color: #FF6633;"',
                                     'class=\"wysiwyg-color-yellow\"' => 'style="color: #FFCC33;"',
                                     'class=\"wysiwyg-color-green\"' => 'style="color: #009933;"')
    end

end

Here's my controller code:

  def emailblastcreate
    email = Blast.create(blast_params)
    user = current_user
    PanelMailer.blast(user, email).deliver
  end

Can't seem to wrap my head around it, any insight would be great.

John Long
  • 257
  • 2
  • 14

1 Answers1

0

Update

I don't think you have used gsub correctly. Here is one way to re-write your method.

before_save :inliner

def inliner

  regex_hash = {
    Regexp.new(%Q(class="wysiwyg-color-grey"))   => 'style="color: #A9A9A9;"',
    Regexp.new(%Q(class="wysiwyg-color-blue"))   => 'style="color: #333399;"',
    Regexp.new(%Q(class="wysiwyg-color-purple")) => 'style="color: #663399;"',
    Regexp.new(%Q(class="wysiwyg-color-red"))    => 'style="color: #CC3333;"',
    Regexp.new(%Q(class="wysiwyg-color-orange")) => 'style="color: #FF6633;"',
    Regexp.new(%Q(class="wysiwyg-color-yellow")) => 'style="color: #FFCC33;"',
    Regexp.new(%Q(class="wysiwyg-color-green"))  => 'style="color: #009933;"'
  }

  regex_hash.each do |regex_exp, val|
    self.body.gsub!(regex_exp, val)
  end

end

You can also refer to following to improve the syntax further:

Ruby gsub multiple characters in string

Ruby multiple string replacement

Community
  • 1
  • 1
Utsav Kesharwani
  • 1,715
  • 11
  • 25