Sha256: 9e842a5cddb387bf4768285fa7e25b02b42bdee5f4a6e5917a9048c70ff00276

Contents?: true

Size: 1.16 KB

Versions: 6

Compression:

Stored size: 1.16 KB

Contents

require 'yaml'

YAML.add_builtin_type("omap") do |type, val|
  CoreExt::OrderedHash[val.map{ |v| v.to_a.first }]
end

module CoreExt
  # <tt>CoreExt::OrderedHash</tt> implements a hash that preserves
  # insertion order.
  #
  #   oh = CoreExt::OrderedHash.new
  #   oh[:a] = 1
  #   oh[:b] = 2
  #   oh.keys # => [:a, :b], this order is guaranteed
  #
  # Also, maps the +omap+ feature for YAML files
  # (See http://yaml.org/type/omap.html) to support ordered items
  # when loading from yaml.
  #
  # <tt>CoreExt::OrderedHash</tt> is namespaced to prevent conflicts
  # with other implementations.
  class OrderedHash < ::Hash
    def to_yaml_type
      "!tag:yaml.org,2002:omap"
    end

    def encode_with(coder)
      coder.represent_seq '!omap', map { |k,v| { k => v } }
    end

    def select(*args, &block)
      dup.tap { |hash| hash.select!(*args, &block) }
    end

    def reject(*args, &block)
      dup.tap { |hash| hash.reject!(*args, &block) }
    end

    def nested_under_indifferent_access
      self
    end

    # Returns true to make sure that this hash is extractable via <tt>Array#extract_options!</tt>
    def extractable_options?
      true
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
core_ext-0.0.6 lib/core_ext/ordered_hash.rb
core_ext-0.0.5 lib/core_ext/ordered_hash.rb
core_ext-0.0.4 lib/core_ext/ordered_hash.rb
core_ext-0.0.3 lib/core_ext/ordered_hash.rb
core_ext-0.0.2 lib/core_ext/ordered_hash.rb
core_ext-0.0.1 lib/core_ext/ordered_hash.rb