Module: Mws::Utils

Extended by:
Utils
Included in:
Utils
Defined in:
lib/mws/utils.rb

Overview

This module contains a collection of generally useful methods that (currently) have no better place to live. They can either be referenced directly as module methods or be mixed in.

Instance Method Summary collapse

Instance Method Details

#alias(to, from, *constants) ⇒ Object



40
41
42
43
44
45
46
47
48
# File 'lib/mws/utils.rb', line 40

def alias(to, from, *constants)
  constants.each do | name |
    constant = from.const_get(name)
    to.singleton_class.send(:define_method, name) do | *args, &block |
      constant.new *args, &block
    end
    to.const_set(name, constant)
  end
end

#camelize(name, uc_first = true) ⇒ String

This method will derive a camelized name from the provided underscored name.

Parameters:

  • name (#to_s)

    The underscored name to be camelized.

  • uc_first (Boolean) (defaults to: true)

    True if and only if the first letter of the resulting camelized name should be capitalized.

Returns:

  • (String)

    The camelized name corresponding to the provided underscored name.



13
14
15
16
17
18
19
20
21
# File 'lib/mws/utils.rb', line 13

def camelize(name, uc_first=true)
  return nil if name.nil?
  name = name.to_s.strip
  return name if name.empty?
  parts = name.split '_'
  assemble = lambda { |head, tail| head + tail.capitalize }
  parts[0] = uc_first ? parts[0].capitalize : parts[0].downcase
  parts.inject(&assemble)
end

#underscore(name) ⇒ Object



23
24
25
26
27
28
29
30
31
32
# File 'lib/mws/utils.rb', line 23

def underscore(name)
  return nil if name.nil?
  name = name.to_s.strip
  return name if name.empty?
  name.gsub(/::/, '/')
    .gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2')
    .gsub(/([a-z\d])([A-Z])/,'\1_\2')
    .tr("-", "_")
    .downcase
end

#uri_escape(value) ⇒ Object



34
35
36
37
38
# File 'lib/mws/utils.rb', line 34

def uri_escape(value)
  value.gsub /([^a-zA-Z0-9_.~-]+)/ do
    '%' + $1.unpack('H2' * $1.bytesize).join('%').upcase
  end
end