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’ ‘fooBar’.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’ ‘fooBar’.constantize => ‘FooBar’

Raises:

  • (Exception)


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

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

#nmtokenize(sym = :under_score) ⇒ String

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

Parameters:

  • sym (Symbol) (defaults to: :under_score)

    optional setting for what type of nmtoken desired: either :snakeCase or :under_score

Returns:

  • (String)

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



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/duxml/ruby_ext/string.rb', line 21

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