Sha256: 2d379022beb6f9dbf9adc01f5b5773cb83728be4f1e9c8f21319f6397dfc7cfd

Contents?: true

Size: 1.25 KB

Versions: 2

Compression:

Stored size: 1.25 KB

Contents

# Similar to Ruby's OpenStruct but uses hash as its parent class providing
# all of the typical Hash methods. Useful for storing settings on objects.
module BBLib
  class HashStruct < Hash

    protected

    def method_missing(method, *args, &block)
      if args.empty? && ![:to_ary].include?(method)
        if method.to_s.end_with?('?')
          define_singleton_method(method) do
            self[method[0..-2].to_sym] ? true : false
          end
          send(method)
        else
          define_singleton_method(method) do
            self[method]
          end
          self[method]
        end
      elsif method.to_s.end_with?('=')
        define_singleton_method(method) do |arg|
          self[method[0..-2].to_sym] = arg
        end
        self[method[0..-2].to_sym] = args.first
      else
        super
      end
    end

    def respond_to_missing?(method, include_private = false)
      include?(method) || method.to_s =~ /\?|\=/ && include?(method.to_s[0..-2].to_sym) || super
    end
  end
end

class Hash
  def to_hash_struct(recursive = true)
    hash = recursive ? self.hmap { |k, v| [k, v.respond_to?(:to_hash_struct) ? v.to_hash_struct(recursive) : v] } : self
    BBLib::HashStruct.new.merge(hash)
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
bblib-2.0.5 lib/bblib/core/classes/hash_struct.rb
bblib-2.0.4 lib/bblib/core/classes/hash_struct.rb