Class: Munson::KeyFormatter

Inherits:
Object show all
Defined in:
lib/munson/key_formatter.rb

Instance Method Summary collapse

Constructor Details

#initialize(resource_key_format) ⇒ KeyFormatter

Returns a new instance of KeyFormatter.

Parameters:

  • resource_key_format (Symbol)


3
4
5
# File 'lib/munson/key_formatter.rb', line 3

def initialize(resource_key_format)
  @format = resource_key_format
end

Instance Method Details

#externalize(hash) ⇒ Object

Converts underscored keys to ‘format`



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/munson/key_formatter.rb', line 8

def externalize(hash)
  deep_transform_keys(hash) do |key|
    if @format == :dasherize
      dasherize(key)
    elsif @format == :camelize
      camelize(key)
    else
      raise UnrecognizedKeyFormatter, <<-ERR
      No key formatter found for `#{@format}`.

      Valid :key_format values are `:camelize` and `:underscore`.
      You may also provide a hash of lambdas `{format:->(key){}, unformat:->(key){}}`
      ERR
    end
  end
end

#internalize(hash) ⇒ Object

Converts keys formatted in ‘format` to underscore



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/munson/key_formatter.rb', line 26

def internalize(hash)
  deep_transform_keys(hash) do |key|
    if @format == :dasherize
      undasherize(key)
    elsif @format == :camelize
      underscore(key)
    else
      raise UnrecognizedKeyFormatter, <<-ERR
      No key formatter found for `#{@format}`.

      Valid :key_format values are `:camelize` and `:underscore`.
      You may also provide a hash of lambdas `{format:->(key){}, unformat:->(key){}}`
      ERR
    end
  end
end