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


how can programmatically turn class name, foobar, symbol, :foo_bar? e.g. this, handles camel case properly?

foobar.to_s.downcase.to_sym 

rails comes method called underscore allow transform camelcased strings underscore_separated strings. might able this:

foobar.name.underscore.to_sym 

but have install activesupport that, ipsum says.

if don't want install activesupport that, can monkey-patch underscore string (the underscore function 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   end end 

Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -