Sha256: 8dfe076540238663115117d7fb1572c09c6a4f74980dd9c3cfec15fc24e91f54

Contents?: true

Size: 759 Bytes

Versions: 9

Compression:

Stored size: 759 Bytes

Contents

# frozen_string_literal: true
# rubocop:todo all

# 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

9 entries across 9 versions & 2 rubygems

Version Path
mongo-2.21.0 spec/support/keyword_struct.rb
mongo-2.20.1 spec/support/keyword_struct.rb
mogno-2.20.0 spec/support/keyword_struct.rb
mogno-1.0.0 spec/support/keyword_struct.rb
mongo-2.20.0 spec/support/keyword_struct.rb
mongo-2.19.3 spec/support/keyword_struct.rb
mongo-2.19.2 spec/support/keyword_struct.rb
mongo-2.19.1 spec/support/keyword_struct.rb
mongo-2.19.0 spec/support/keyword_struct.rb