Sha256: c7e8dbc7aaae79a3fa670b0c748b19453b47a24f6b7c161cd99d389872cd8fbd

Contents?: true

Size: 1.31 KB

Versions: 19

Compression:

Stored size: 1.31 KB

Contents

class Hash::KeyChanger
  attr_reader :hash, :block

  def initialize(hash)
    @hash = hash
  end

  def change_keys(settings = {}, &block)
    merge_options({
      recursive: true
    }, settings)

    if options[:recursive]
      hash.deep_transform_keys!(&block)
    else
      hash.transform_keys!(&block)
    end
  end

  def camelize_keys(settings = {})
    merge_options({
      uppercase_first_letter: true
    }, settings)

    type = options[:uppercase_first_letter] ? :upper : :lower

    change_keys do |k|
      k.camelize(type)
    end
  end

  def underscore_keys(settings = {})
    merge_options({}, settings)

    change_keys do |k|
      k.underscore
    end
  end

  def change_text(options = {}, &block)
    merge_options({
      type: :keep
    }, options)

    change_keys do |key|
      cast_new_key block.call(key), key.class
    end
  end

  private

  def merge_options(default, custom)
    @options = {}.merge!(default).merge!(custom).merge!(options)
  end

  def options
    @options ||= {}
  end

  def cast_new_key(key, old_clazz)
    case class_cast(old_clazz)
    when :symbol then
      key.to_sym
    when :string then
      key.to_s
    end
  end

  def keep_class?
    options[:type] == :keep
  end

  def class_cast(old_clazz)
    keep_class? && old_clazz.to_s.downcase.to_sym || options[:type]
  end
end

Version data entries

19 entries across 19 versions & 2 rubygems

Version Path
darthjee-core_ext-1.5.6 lib/darthjee/core_ext/hash/key_changer.rb
darthjee-core_ext-1.5.5 lib/darthjee/core_ext/hash/key_changer.rb
darthjee-core_ext-1.5.4 lib/darthjee/core_ext/hash/key_changer.rb
darthjee-core_ext-1.5.3 lib/darthjee/core_ext/hash/key_changer.rb
darthjee-core_ext-1.5.2 lib/darthjee/core_ext/hash/key_changer.rb
darthjee-core_ext-1.5.1 lib/darthjee/core_ext/hash/key_changer.rb
darthjee-core_ext-1.5.0 lib/darthjee/core_ext/hash/key_changer.rb
darthjee-core_ext-1.4.1 lib/darthjee/core_ext/hash/key_changer.rb
darthjee-core_ext-1.4.0 lib/darthjee/core_ext/hash/key_changer.rb
darthjee-core_ext-1.3.1 lib/hash/key_changer.rb
darthjee-core_ext-1.3.0 lib/hash/key_changer.rb
darthjee-core_ext-1.2.6 lib/hash/key_changer.rb
bidu-core_ext-1.2.5 lib/hash/key_changer.rb
bidu-core_ext-1.2.4 lib/hash/key_changer.rb
bidu-core_ext-1.2.3 lib/hash/key_changer.rb
bidu-core_ext-1.2.2 lib/hash/key_changer.rb
bidu-core_ext-1.2.1 lib/hash/key_changer.rb
bidu-core_ext-1.2.0 lib/hash/key_changer.rb
bidu-core_ext-1.1.1 lib/hash/key_changer.rb