Sha256: 20c3f93a717767bcd7781ad4006690256c75992d303120e6796ed588770c934e

Contents?: true

Size: 758 Bytes

Versions: 18

Compression:

Stored size: 758 Bytes

Contents

# frozen_string_literal: true
# encoding: utf-8

# Intermediate step between a Struct and an OpenStruct. Allows only designated
# field names to be read or written but allows passing fields to constructor
# as keyword arguments.
class KeywordStruct
  def self.new(*field_names, &block)
    Class.new.tap do |cls|
      cls.class_exec do
        define_method(:initialize) do |**fields|
          fields.each do |field, value|
            unless field_names.include?(field)
              raise ArgumentError, "Unknown field #{field}"
            end

            instance_variable_set("@#{field}", value)
          end
        end

        attr_accessor *field_names
      end

      if block_given?
        cls.class_exec(&block)
      end
    end
  end
end

Version data entries

18 entries across 18 versions & 1 rubygems

Version Path
mongo-2.16.4 spec/support/keyword_struct.rb
mongo-2.17.4 spec/support/keyword_struct.rb
mongo-2.18.3 spec/support/keyword_struct.rb
mongo-2.18.2 spec/support/keyword_struct.rb
mongo-2.17.3 spec/support/keyword_struct.rb
mongo-2.18.1 spec/support/keyword_struct.rb
mongo-2.18.0 spec/support/keyword_struct.rb
mongo-2.17.2 spec/support/keyword_struct.rb
mongo-2.16.3 spec/support/keyword_struct.rb
mongo-2.18.0.beta1 spec/support/keyword_struct.rb
mongo-2.16.2 spec/support/keyword_struct.rb
mongo-2.17.1 spec/support/keyword_struct.rb
mongo-2.16.1 spec/support/keyword_struct.rb
mongo-2.17.0 spec/support/keyword_struct.rb
mongo-2.16.0 spec/support/keyword_struct.rb
mongo-2.15.1 spec/support/keyword_struct.rb
mongo-2.16.0.alpha1 spec/support/keyword_struct.rb
mongo-2.15.0 spec/support/keyword_struct.rb