views:

252

answers:

1

Currently I am using this to strip out whitespaces.

class Newsletter < ActiveRecord::Base
  before_validation :clean_up_whitespace
end


def clean_up_whitespace 

fields_to_strip = ['title','notes']
 fields_to_strip.each { |f|
   unless self.attributes[f].nil?
      self.attributes[f].strip!
   end
 }
end


I want to do something similar for getting rid of MS word type of unicode. Currently I use:

require 'iconv'

class Newsletter < ActiveRecord::Base
  before_validation :clean_up_unicode
end

def clean_up_unicode

unless title.blank?
    self.title = Iconv.iconv('ascii//ignore//translit', 'utf-8', self.title).to_s
  end

  unless notes.blank?
    self.notes = Iconv.iconv('ascii//ignore//translit', 'utf-8', self.notes).to_s
  end
end


This method works but is not very DRY since I need to do it for 40 some form fields.

I had thought I could use something like:

require 'iconv'

class Newsletter < ActiveRecord::Base
  before_validation :clean_up_unicode
end

def clean_up_unicode 

unicode_fields_to_clean = ['title','notes']
   unicode_fields_to_clean.each { |u|
    unless self.attributes[u].blank?
       self.attributes[u] = Iconv.iconv('ascii//ignore//translit', 'utf-8', attributes[u]).to_s
   end
 }
end


I know I am not understanding something with the way this works.
when I replace

self.attributes[u] =
with
*puts some_variable =*

I get the correct output to the console. I just don't know how to get that variable back to the form.

If it helps the code that is wrong is self.attributes[u] = I don't know what to replace it with. I would have thought I could use self.VariableNameOfField = but rails does not recognise the variable being used directly like that.

+1  A: 

Ok, so with some help from:
John Topley and Jakob S
(sorry as a new user cannot only have 1 hyperlink and thus cannot link to their stack-overflow profiles)

And asking a simpler stack-overflow question

I have been able to come up with the following code that works.
The trick was changing.

self.attributes[u] = Iconv.iconv('ascii//ignore//translit', 'utf-8', attributes[u]).to_s

to

self.send("#{u}=", Iconv.iconv('ascii//ignore//translit', 'utf-8', attributes[u]).to_s)

The Working Code


require 'iconv'

class Newsletter < ActiveRecord::Base
  before_validation :clean_up_unicode
end

def clean_up_unicode 

unicode_fields_to_clean = ['title','notes']
   unicode_fields_to_clean.each { |u|
    unless self.attributes[u].blank?
       self.send("#{u}=", Iconv.iconv('ascii//ignore//translit', 'utf-8', attributes[u]).to_s)
   end
 }
end
Datatec