Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get human readable class name in Ruby on Rails?

I am building an application with Ruby 1.9.3 and Rails 3.0.9

I have a class like below.

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

I want the class name like "CDADocument".

Is my humanize_class_name method is the correct way to achieve this?

OR

Any other built in methods available with Rails?

like image 334
Soundar Rathinasamy Avatar asked Sep 10 '12 10:09

Soundar Rathinasamy


2 Answers

If you using i18n you can call Model.model_name.human to get the localized model name.

E.g.: Event.model_name.human returns my localized name.

Docs: http://api.rubyonrails.org/classes/ActiveModel/Name.html#method-i-human

like image 56
Max Avatar answered Oct 13 '22 17:10

Max


I think Rails might have something similar, but since the form you want is peculiar, you will have to design the method by yourself. The position where you define it is wrong. You would have to do that for each class. Instead, you should define it in Class class.

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

or

class Object
    def humanize_class_name
        self.class.name.delete(":")
    end
end
some_instance.humanize_class_name #=> the string you want
like image 1
sawa Avatar answered Oct 13 '22 18:10

sawa