Sinatra Title Slugs

时间:2010-04-17 23:23:52

标签: ruby sinatra helpers slug

我正在尝试在Sinatra创建一个slug帮手。这是代码(如here所示):

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

究竟出了什么问题?

3 个答案:

答案 0 :(得分:1)

“到底出了什么问题?”

嗯,错误信息有点不言自明。您将此方法的标题变量设置为 nil 。要重现错误,请尝试调用:

slugify(nil)

我想它在这一行上失败了:

title = title.gsub(s, rep)

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

raise "wrong input!" if title.nil?

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

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

BTW你的代码可能会使用一些严重的重构。首先,尝试替换:

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

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

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

"woot".tr("wt","WT") # => "WooT"

答案 1 :(得分: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

答案 2 :(得分:0)

看看iconv的音译能力。它可以让你避免建立自己的角色转换表。

Obie Fernandez救援:http://www.jroller.com/obie/tags/unicode