我正在使用Ruby 1.9.3和Rails 3.0.9构建应用程序
我有一个类似下面的课程。
module CDA
class Document
def humanize_class_name
self.class.name.gsub("::","")
end
end
end
我想要类名“CDADocument”。
我的humanize_class_name方法是否是实现此目的的正确方法?
OR
Rails提供的任何其他内置方法?
答案 0 :(得分:19)
如果您使用i18n
,则可以致电Model.model_name.human
获取本地化的型号名称。
例如:Event.model_name.human
返回我的本地化名称。
文档:http://api.rubyonrails.org/classes/ActiveModel/Name.html#method-i-human
答案 1 :(得分: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