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



219
220
221
222
223
224
225
226
227
228
229
230
231
232
# File 'lib/class2.rb', line 219

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