How do I convert a Ruby class name to a underscore-delimited symbol? How do I convert a Ruby class name to a underscore-delimited symbol? ruby ruby

How do I convert a Ruby class name to a underscore-delimited symbol?


Rails comes with a method called underscore that will allow you to transform CamelCased strings into underscore_separated strings. So you might be able to do this:

FooBar.name.underscore.to_sym

But you will have to install ActiveSupport just to do that, as ipsum says.

If you don't want to install ActiveSupport just for that, you can monkey-patch underscore into String yourself (the underscore function is defined in ActiveSupport::Inflector):

class String  def underscore    word = self.dup    word.gsub!(/::/, '/')    word.gsub!(/([A-Z]+)([A-Z][a-z])/,'\1_\2')    word.gsub!(/([a-z\d])([A-Z])/,'\1_\2')    word.tr!("-", "_")    word.downcase!    word  endend


Rails 4 .model_name

In Rails 4, it returns an ActiveModel::Name object which contains many useful more "semantic" attributes such as:

FooBar.model_name.param_key#=> "foo_bar"FooBar.model_name.route_key#=> "foo_bars"FooBar.model_name.human#=> "Foo bar"

So you should use one of those if they match your desired meaning, which is likely the case. Advantages:

  • easier to understand your code
  • your app will still work even in the (unlikely) event that Rails decides to change a naming convention.

BTW, human has the advantage of being I18N aware.


first: gem install activesupport

require 'rubygems'require 'active_support'"FooBar".underscore.to_sym