Module: Class2::StrictConstructor

Defined in:
lib/class2.rb

Overview

By default unknown arguments are ignored. <code>include<code>ing this will cause an ArgumentError to be raised if an attribute is unknown:

Class Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



239
240
241
242
243
244
245
246
247
248
249
250
251
252
# File 'lib/class2.rb', line 239

def self.included(klass)
  klass.class_eval do
    def initialize(attributes = nil)
      return unless attributes.is_a?(Hash)
      assign_attributes(attributes)

      accepted = to_h.keys
      attributes.each do |name, _|
        next if accepted.include?(name.respond_to?(:to_sym) ? name.to_sym : name)
        raise ArgumentError, "unknown attribute: #{name}"
      end
    end
  end
end