0

我正在尝试在 Sinatra 中创建一个 slug 助手。这是代码(如此处所示

helpers do
  def sluggify(title)
  accents = { 
    ['á','à','â','ä','ã'] => 'a',
    ['Ã','Ä','Â','À'] => 'A',
    ['é','è','ê','ë'] => 'e',
    ['Ë','É','È','Ê'] => 'E',
    ['í','ì','î','ï'] => 'i',
    ['Î','Ì'] => 'I',
    ['ó','ò','ô','ö','õ'] => 'o',
    ['Õ','Ö','Ô','Ò','Ó'] => 'O',
    ['ú','ù','û','ü'] => 'u',
    ['Ú','Û','Ù','Ü'] => 'U',
    ['ç'] => 'c', ['Ç'] => 'C',
    ['ñ'] => 'n', ['Ñ'] => 'N'
  }

  accents.each do |ac,rep|
    ac.each do |s|
      title = title.gsub(s, rep)
    end
  end

  title = title.gsub(/[^a-zA-Z0-9 ]/,"")
  title = title.gsub(/[ ]+/," ")    
  title = title.gsub(/ /,"-")
  title = title.downcase

end

end

我不断收到此错误:

private method `gsub' called for nil:NilClass

到底出了什么问题?

4

3 回答 3

1

“究竟出了什么问题?”

好吧,错误消息有点不言自明。您在 title 变量设置为nil的情况下调用了此方法。要重现错误,请尝试调用:

slugify(nil)

我想它在这条线上失败了:

title = title.gsub(s, rep)

为避免这种情况,您可以在方法的开头检查nil标题:

raise "wrong input!" if title.nil?

或(恕我直言,更优雅)总是将标题转换为字符串,最终将nil转换为空字符串:

title = title.to_s # "any string" => "any string", nil => ""

顺便说一句,您的代码可能会使用一些严重的重构。首先,尝试替换:

title = title.gsub(/a/,/b/)

title.gsub!(/a/,/b/)

或使用tr方法代替gsub进行字符到字符替换:

"woot".tr("wt","WT") # => "WooT"
于 2010-05-03T11:38:27.670 回答
0

我无法复制您所看到的内容。这是我的测试(在 Sinatra 之外,所以只使用一个模块):

module Helpers
  def self.sluggify(title)
    accents = {['á','à','â','ä','ã'] => 'a'} # Shortened

    accents.each do |ac,rep|
      ac.each do |s|
        title = title.gsub(s, rep)
      end
    end

    title = title.gsub(/[^a-zA-Z0-9 ]/,"")
    title = title.gsub(/[ ]+/," ")    
    title = title.gsub(/ /,"-")
    title = title.downcase
  end
end

puts Helpers.sluggify("Testing this!")

产量testing-this

于 2010-04-18T04:38:34.487 回答
0

看看iconv的音译能力。它可以让您避免建立自己的字符转换表。

奥比费尔南德斯救援:http ://www.jroller.com/obie/tags/unicode

于 2010-04-18T07:00:42.933 回答