Sha256: 94c42634f35c7b13192f9a7ed6cb242ccb553145ff2944f4ecd844acf09793d7

Contents?: true

Size: 964 Bytes

Versions: 1

Compression:

Stored size: 964 Bytes

Contents

class Hash
  class << self
    attr_accessor :use_dot_syntax
  end

  attr_accessor :use_dot_syntax

  def to_dot
    dotify_hash(self)

    self
  end

  def method_missing(method, *args)
    return super(method, *args) unless to_dot?

    prop = create_prop(method)

    if self[prop].nil? && prop_present?(prop)
      self[prop] = self.delete(prop.to_s)
    end

    super(method, args) and return unless prop_present?(prop)

    if setter?(method)
      self[prop] = args.first
    else
      self[prop]
    end
  end

  private

  def dotify_hash(hash)
    hash.use_dot_syntax = true

    hash.keys.each { |key| dotify_hash(hash[key]) if hash[key].is_a?(Hash) }
  end

  def to_dot?
    self.use_dot_syntax || self.class.use_dot_syntax
  end

  def setter?(method)
    method.last == "="
  end

  def create_prop(method)
    setter?(method) ? method.chop : method
  end

  def prop_present?(prop)
    self.has_key?(prop) || self.has_key?(prop.to_s)
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
hash_dot-2.0.1 lib/hash.rb