Class: String

Inherits:
Object show all
Defined in:
lib/duxml/ruby_ext/string.rb

Instance Method Summary collapse

Instance Method Details

#constantizeString

Returns converts string into Ruby constant. self must be String with no whitespaces and match Regexp.nmtoken ‘foo-bar’.constantize => ‘Foo_bar’ ‘foo_bar’.constantize => ‘FooBar’.

Returns:

  • (String)

    converts string into Ruby constant. self must be String with no whitespaces and match Regexp.nmtoken ‘foo-bar’.constantize => ‘Foo_bar’ ‘foo_bar’.constantize => ‘FooBar’

Raises:

  • (Exception)


8
9
10
11
12
13
14
# File 'lib/duxml/ruby_ext/string.rb', line 8

def constantize
  return self if Regexp.constant.match(self)
  raise Exception unless Regexp.nmtoken.match(self)
  s = split('_').collect do |word| word.capitalize unless word == '_' end.join.gsub('-', '_')
  raise Exception unless s.match(Regexp.constant)
  s
end

#nmtokenizeString

Returns does reverse of #constantize e.g. ‘Foo_b’.nmtokenize => ‘foo-bar’ ‘FooBar’.nmtokenize => ‘foo_bar’.

Returns:

  • (String)

    does reverse of #constantize e.g. ‘Foo_b’.nmtokenize => ‘foo-bar’ ‘FooBar’.nmtokenize => ‘foo_bar’



19
20
21
22
23
24
25
26
27
28
# File 'lib/duxml/ruby_ext/string.rb', line 19

def nmtokenize
  split('::').collect do |word|
    word.gsub(/(?!^)[A-Z_]/) do |match|
      case match
        when '_' then '-'
        else "_#{match.downcase}"
      end
    end.downcase
  end.join(':')
end