Module: TwitterCldr::Utils

Defined in:
lib/twitter_cldr/utils.rb,
lib/twitter_cldr/utils/code_points.rb,
lib/twitter_cldr/utils/interpolation.rb

Defined Under Namespace

Modules: CodePoints

Constant Summary collapse

HASH_INTERPOLATION_REGEXP =
Regexp.union(
    /%\{(\w+)\}/,
    /%<(\w+)>(.*?\d*\.?\d*[bBdiouxXeEfgGcps])/
)
HASH_INTERPOLATION_WITH_ESCAPE_REGEXP =
Regexp.union(
    /%%/,
    HASH_INTERPOLATION_REGEXP
)

Class Method Summary collapse

Class Method Details

.deep_symbolize_keys(arg) ⇒ Object

adapted from: snippets.dzone.com/posts/show/11121 (first comment)



14
15
16
17
18
19
20
21
22
23
# File 'lib/twitter_cldr/utils.rb', line 14

def deep_symbolize_keys(arg)
  case arg
    when Array
      arg.map { |elem| deep_symbolize_keys(elem) }
    when Hash
      Hash[arg.map { |k, v| [k.is_a?(String) ? k.to_sym : k, deep_symbolize_keys(v)] }]
    else
      arg
  end
end

.interpolate(string, args) ⇒ Object

Uses string as a format specification and returns the result of applying it to args.

There are three ways to use it:

  • Using a single argument or Array of arguments.

    This is the default behaviour of the String#% method. See Kernel#sprintf for more details about the format specification.

    Example:

    TwitterCldr::Utils.interpolate('%d %s', [1, 'message'])
    # => "1 message"
    
  • Using a Hash as an argument and unformatted, named placeholders (Ruby 1.9 syntax).

    When you pass a Hash as an argument and specify placeholders with %foo it will interpret the hash values as named arguments.

    Example:

    TwitterCldr::Utils.interpolate('%{firstname}, %{lastname}', :firstname => 'Masao', :lastname => 'Mutoh')
    # => "Masao Mutoh"
    
  • Using a Hash as an argument and formatted, named placeholders (Ruby 1.9 syntax).

    When you pass a Hash as an argument and specify placeholders with %<foo>d it will interpret the hash values as named arguments and format the value according to the formatting instruction appended to the closing >.

    Example:

    TwitterCldr::Utils.interpolate('%<integer>d, %<float>.1f', :integer => 10, :float => 43.4)
    # => "10, 43.3"
    

An exception can be thrown in two cases when Ruby 1.9 interpolation syntax is used:

  • ArgumentError is thrown if Ruby 1.9. interpolation syntax is used in string, but args is not a Hash;

  • KeyError is thrown if the value for one of the placeholders in string is missing in args hash.



78
79
80
# File 'lib/twitter_cldr/utils/interpolation.rb', line 78

def interpolate(string, args)
  string =~ HASH_INTERPOLATION_REGEXP ? interpolate_hash(string, args) : interpolate_value_or_array(string, args)
end