Sha256: 0c16e45a91990879bc7715608e16c3c71997f5ceb7aecfc18e96e601db32067a

Contents?: true

Size: 1.25 KB

Versions: 22

Compression:

Stored size: 1.25 KB

Contents

# frozen_string_literal: true

require 'active_support/hash_with_indifferent_access'
require 'active_support/core_ext/object/blank'

module EacRubyUtils
  class Struct
    def initialize(initial_data = {})
      self.data = ::ActiveSupport::HashWithIndifferentAccess.new(initial_data)
    end

    def [](key)
      key, bool = parse_key(key)
      bool ? self[key].present? : data[key]
    end

    def fetch(key)
      key, bool = parse_key(key)
      bool ? fetch(key).present? : data.fetch(key)
    end

    def method_missing(method_name, *arguments, &block)
      property_method?(method_name) ? fetch(method_name) : super
    end

    def respond_to_missing?(method_name, include_private = false)
      property_method?(method_name) || super
    end

    def slice_fetch(*keys)
      self.class.new(keys.map { |key| [key, fetch(key)] }.to_h)
    end

    def to_h
      data.dup
    end

    delegate :to_s, to: :data

    private

    attr_accessor :data

    def parse_key(key)
      m = /\A(.+)\?\z/.match(key.to_s)
      [(m ? m[1] : key.to_s).to_sym, m ? true : false]
    end

    def property_method?(key)
      property_methods.include?(key.to_sym)
    end

    def property_methods
      data.keys.flat_map { |k| [k.to_sym, "#{k}?".to_sym] }
    end
  end
end

Version data entries

22 entries across 22 versions & 3 rubygems

Version Path
eac_ruby_utils-0.55.0 lib/eac_ruby_utils/struct.rb
avm-tools-0.80.0 vendor/eac_ruby_utils/lib/eac_ruby_utils/struct.rb
avm-tools-0.79.0 vendor/eac_ruby_utils/lib/eac_ruby_utils/struct.rb
avm-tools-0.78.0 vendor/eac_ruby_utils/lib/eac_ruby_utils/struct.rb
ehbrs-tools-0.16.2 vendor/eac_ruby_utils/lib/eac_ruby_utils/struct.rb
eac_ruby_utils-0.54.0 lib/eac_ruby_utils/struct.rb
eac_ruby_utils-0.53.0 lib/eac_ruby_utils/struct.rb
avm-tools-0.77.0 vendor/eac_ruby_utils/lib/eac_ruby_utils/struct.rb
eac_ruby_utils-0.52.0 lib/eac_ruby_utils/struct.rb
ehbrs-tools-0.16.1 vendor/eac_ruby_utils/lib/eac_ruby_utils/struct.rb
eac_ruby_utils-0.51.1 lib/eac_ruby_utils/struct.rb
avm-tools-0.76.1 vendor/eac_ruby_utils/lib/eac_ruby_utils/struct.rb
eac_ruby_utils-0.51.0 lib/eac_ruby_utils/struct.rb
eac_ruby_utils-0.50.0 lib/eac_ruby_utils/struct.rb
ehbrs-tools-0.16.0 vendor/eac_ruby_utils/lib/eac_ruby_utils/struct.rb
avm-tools-0.76.0 vendor/eac_ruby_utils/lib/eac_ruby_utils/struct.rb
eac_ruby_utils-0.49.1 lib/eac_ruby_utils/struct.rb
avm-tools-0.75.1 vendor/eac_ruby_utils/lib/eac_ruby_utils/struct.rb
avm-tools-0.75.0 vendor/eac_ruby_utils/lib/eac_ruby_utils/struct.rb
avm-tools-0.74.1 vendor/eac_ruby_utils/lib/eac_ruby_utils/struct.rb