Module: Hashie::Extensions::IgnoreUndeclared

Defined in:
lib/hashie/extensions/ignore_undeclared.rb

Overview

IgnoreUndeclared is a simple mixin that silently ignores undeclared properties on initialization instead of raising an error. This is useful when using a Trash to capture a subset of a larger hash.

Note that attempting to retrieve or set an undeclared property will still raise a NoMethodError, even if a value for that property was provided at initialization.

Examples:

class Person < Trash
  include Hashie::Extensions::IgnoreUndeclared

  property :first_name
  property :last_name
end

user_data = {
   :first_name => 'Freddy',
   :last_name => 'Nostrils',
   :email => '[email protected]'
}

p = Person.new(user_data) # 'email' is silently ignored

p.first_name # => 'Freddy'
p.last_name  # => 'Nostrils'
p.email      # => NoMethodError

Instance Method Summary collapse

Instance Method Details

#initialize_attributes(attributes) ⇒ Object



32
33
34
35
36
37
38
39
# File 'lib/hashie/extensions/ignore_undeclared.rb', line 32

def initialize_attributes(attributes)
  return unless attributes

  klass = self.class
  translations = klass.respond_to?(:translations) && klass.translations || []

  super(attributes.select { |attr, _| klass.property?(attr) || translations.include?(attr) })
end

#property_exists?(property) ⇒ Boolean

Returns:

  • (Boolean)


41
42
43
# File 'lib/hashie/extensions/ignore_undeclared.rb', line 41

def property_exists?(property)
  self.class.property?(property)
end