Module: Protobuf::Util

Defined in:
lib/protobuf/common/util.rb

Class Method Summary collapse

Class Method Details

.camelize(str) ⇒ Object

Takes a string or symbol and camelizes it: Expects: some_long_name Returns: SomeLongName



8
9
10
11
12
13
14
# File 'lib/protobuf/common/util.rb', line 8

def camelize(str)
  if (str.is_a? Array)
    str.map{|p| camelize(p.to_s) }.join('::')
  else
    str.to_s.gsub(/(?:\A|_)(\w)/) { $1.upcase }
  end
end

.constantize(klass) ⇒ Object



53
54
55
56
# File 'lib/protobuf/common/util.rb', line 53

def constantize(klass)
  constants = moduleize(klass).split('::')
  constants.inject(Module.const_get(constants.shift)) {|const, obj| const.const_get(obj) }
end

.module_to_path(str) ⇒ Object

Expects: SomeModule::Path Returns: some_module/path



24
25
26
27
# File 'lib/protobuf/common/util.rb', line 24

def module_to_path(str)
  pkg = str.to_s.split('::')
  pkg.map{|e| underscore(e) }.join('/')
end

.moduleize(str) ⇒ Object

The reverse of packagize. Takes a string resembling a java package path and converts it into a module constant Expects: mod_a.mod_b.MyService Returns: ModA::ModB::MyService



48
49
50
51
# File 'lib/protobuf/common/util.rb', line 48

def moduleize(str)
  str = str.join('.') if str.is_a? Array
  str.split('.').map{|e| camelize(e) }.join('::')
end

.package_to_path(str) ⇒ Object

Expects: PackageA.PackageB Returns: package_a/package_b



31
32
33
# File 'lib/protobuf/common/util.rb', line 31

def package_to_path(str)
  str.to_s.split('.').map{|e| underscore(e) }.join('/')
end

.packagize(klass) ⇒ Object

Takes a class constant and converts it to a string resembling a java package path Expects: ModA::ModB::MyService Returns: mod_a.mod_b.MyService



38
39
40
41
42
# File 'lib/protobuf/common/util.rb', line 38

def packagize(klass)
  klass = klass.to_s.split('::') unless klass.is_a? Array
  klass_name = klass.pop
  klass.map{|e| underscore(e) }.join('.') + ".#{klass_name}"
end

.underscore(str) ⇒ Object

Expects: SomeLongName Returns: some_long_name



18
19
20
# File 'lib/protobuf/common/util.rb', line 18

def underscore(str)
  str.to_s.gsub(/\B[A-Z]/, '_\&').downcase
end