Friday, May 3, 2013

Replacing –, ’, etc with UTF-8 Characters in Ruby on Rails

It was getting cumbersome to update these non-utf8 compatible characters time to time!

substitutions = []
substitutions << ['…', '…']           # elipsis
substitutions << ['–', '–']           # long hyphen
substitutions << ['’', "'"]           # curly apostrophe
substitutions << ['“', '"']           # curly open quote

klasses = {'Class1' => [:field1, field2], 'Class2' => [:field1, :field2]}
  
klasses.each_pair do |klass, fields|
  klass = klass.constantize
  klass.all.each do |obj|
    fields.each do |field|
      if obj.send(field).present?
        substitutions.each do |set| 
          obj.send(field.to_s + '=', obj.send(field).gsub(set[0], set[1]))
        end
      end
    end
    
    # Don't fire callback
    klass.skip_callback(:save, :after,  :do_after_save_tasks)
    obj.save!
    
  end
end

No comments:

Post a Comment