Home > Net >  attr_accessor feature not working as expected
attr_accessor feature not working as expected

Time:11-09

I have defined a class like below. But when I run to the format function I get an error like below. Thanks!!!

class NonAccentVietnamese
  def initialize(str)
    @str = str
  end

  def format
    str = str.downcase
    str = str.gsub(/à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ/, "a")
    str = str.gsub(/è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ/, "e")
    str = str.gsub(/ì|í|ị|ỉ|ĩ/, "i")
    str = str.gsub(/ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ/, "o")
    str = str.gsub(/ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ/, "u")
    str = str.gsub(/ỳ|ý|ỵ|ỷ|ỹ/, "y")
    str = str.gsub(/đ/, "d")
    # Some system encode vietnamese combining accent as individual utf-8 characters
    str = str.gsub(/\u0300|\u0301|\u0303|\u0309|\u0323/, "") # Huyền sắc hỏi ngã nặng
    str = str.gsub(/\u02C6|\u0306|\u031B/, "") # Â, Ê, Ă, Ơ, Ư
    str
  end

  private

  attr_accessor :str
end
[2] pry(main)> NonAccentVietnamese.new("Ruby on Rails").format
NoMethodError: undefined method `downcase' for nil:NilClass
from /app-server/app/formats/non_accent_vietnamese.rb:7:in `format'
[3] pry(main)> 

enter image description here

CodePudding user response:

You have local variable name str and an accessor method str, So the local str is being used. What you can do is:

  1. Change the name of the local variable
  2. Change the name of the attr_accessor
  3. Use @str in place of attr_accessor.

CodePudding user response:

You can either use @str.downcase or self.str.downcase.

That being said, you should use the transliterate method:

https://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-transliterate

That will let you use the transliterate methods to replace non-ascii characters with ascii alternatives:

I18n.transliterate("Über der Höhenstraße")
 => "Ueber der Hoehenstrasse"
  • Related