Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/juicer/ext/string.rb

Overview

Additions to core Ruby objects

Instance Method Summary collapse

Instance Method Details

#camel_caseObject

Turn an underscored string into camel case, ie this_becomes -> ThisBecomes



11
12
13
# File 'lib/juicer/ext/string.rb', line 11

def camel_case
  self.split("_").inject("") { |str, piece| str + piece.capitalize }
end

#classify(mod = nil) ⇒ Object

Turn a string in either underscore or camel case form into a class directly



33
34
35
# File 'lib/juicer/ext/string.rb', line 33

def classify(mod = nil)
  self.camel_case.to_class(mod)
end

#to_class(mod = nil) ⇒ Object

Treat a string as a class name and return the class. Optionally provide a module to look up the class in.



21
22
23
24
25
26
# File 'lib/juicer/ext/string.rb', line 21

def to_class(mod = nil)
  res = "#{mod}::#{self}".sub(/^::/, "").split("::").inject(Object) do |mod, obj|
    raise "No such class/module" unless mod.const_defined?(obj)
    mod = mod.const_get(obj)
  end
end

#underscoreObject

Turn a camelcase string into underscore string



42
43
44
# File 'lib/juicer/ext/string.rb', line 42

def underscore
  self.split(/([A-Z][^A-Z]*)/).find_all { |str| str != "" }.join("_").downcase
end