2012-09-10 34 views
7

我正在用Ruby 1.9.3和Rails 3.0.9构建应用程序如何在Ruby on Rails中获得人类可读的类名?

我有一个像下面这样的类。

module CDA 
    class Document 
    def humanize_class_name 
     self.class.name.gsub("::","") 
    end 
    end 
end 

我想要类名如“CDADocument”。

我的humanize_class_name方法是否是实现此目的的正确方法?

OR

任何其他建于使用Rails可用的方法?

回答

1

我觉得Rails可能有类似的东西,但既然你想要的形式是奇特的,你将不得不自己设计方法。你定义它的位置是错误的。你必须为每个班级做到这一点。相反,你应该在Class类中定义它。

class Class 
    def humanize_class_name 
     name.delete(":") 
    end 
end 
some_instance.class.humanize_class_name #=> the string you want 

class Object 
    def humanize_class_name 
     self.class.name.delete(":") 
    end 
end 
some_instance.humanize_class_name #=> the string you want 
+0

仅供参考,'tr'约3.5倍更快这里比'gsub'。 –

+0

@AndrewMarshall我知道'tr'的速度更快,但我不知道你可以把空串作为替换。谢谢。 – sawa

+1

'delete(“:”)'? – Stefan

相关问题