name conversion: search terms?

H

Hugh Sasse

I'm doing some code generation and need to convert from CamelCase to
whatever_this_is_called. Wikipedia has a page for CamelCase but not
underscore separated words.

I'm thinking that someone must have done this already, and got the
edge cases sorted out, so rather than coming up with a wheel with an
iron tyre I'd search... for what? Is there a single correct term
for how we name methods in Ruby?

Thank you,
Hugh
 
B

Bruno Michel

Hugh Sasse a écrit :
I'm doing some code generation and need to convert from CamelCase to
whatever_this_is_called. Wikipedia has a page for CamelCase but not
underscore separated words.

I'm thinking that someone must have done this already, and got the
edge cases sorted out, so rather than coming up with a wheel with an
iron tyre I'd search... for what? Is there a single correct term
for how we name methods in Ruby?

Thank you,
Hugh

Hi,

Ruby on Rails have similar things. You should take a look at Active
Support, and particulary the
ActiveSupport::CoreExtensions::String::Inflections class. The
"underscore" method can be used to transform a string from CamelCase to
underscore_seprated_words.
 
H

Hugh Sasse

Hi,

Ruby on Rails have similar things. You should take a look at Active Support,
and particulary the ActiveSupport::CoreExtensions::String::Inflections class.
The "underscore" method can be used to transform a string from CamelCase to
underscore_seprated_words.

Thank you. That's splendid.Hugh
 
E

Ezra Zygmuntowicz

I'm doing some code generation and need to convert from CamelCase to
whatever_this_is_called. Wikipedia has a page for CamelCase but not
underscore separated words.

I'm thinking that someone must have done this already, and got the
edge cases sorted out, so rather than coming up with a wheel with an
iron tyre I'd search... for what? Is there a single correct term
for how we name methods in Ruby?

Thank you,
Hugh


class String

# "FooBar".snake_case #=> "foo_bar"
def snake_case
return self unless self =~ %r/[A-Z]/
self.reverse.scan(%r/[A-Z]+|[^A-Z]*[A-Z]+?/).reverse.map{|word|
word.reverse.downcase}.join '_'
end

# "foo_bar".camel_case #=> "FooBar"
def camel_case
return self if self =~ %r/[A-Z]/ and self !~ %r/_/
words = self.strip.split %r/\s*_+\s*/
words.map!{|w| w.downcase.sub(%r/^./){|c| c.upcase}}
words.join
end

end


Cheers-
-- Ezra Zygmuntowicz
-- Lead Rails Evangelist
-- (e-mail address removed)
-- Engine Yard, Serious Rails Hosting
-- (866) 518-YARD (9273)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top