Sha256: 108efaa95614b76f1c0f1d92dfda5652e822c50a12d38724ae7b2b9c00a877ee

Contents?: true

Size: 709 Bytes

Versions: 9

Compression:

Stored size: 709 Bytes

Contents

# 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 & 1 rubygems

Version Path
mongo-2.13.3 spec/support/keyword_struct.rb
mongo-2.14.1 spec/support/keyword_struct.rb
mongo-2.15.0.alpha spec/support/keyword_struct.rb
mongo-2.13.2 spec/support/keyword_struct.rb
mongo-2.14.0 spec/support/keyword_struct.rb
mongo-2.14.0.rc1 spec/support/keyword_struct.rb
mongo-2.13.1 spec/support/keyword_struct.rb
mongo-2.13.0 spec/support/keyword_struct.rb
mongo-2.13.0.rc1 spec/support/keyword_struct.rb