module Hashie::Extensions::Mash::RequiredKeys

Extends a Mash with the ability to require specific keys to be set (non-nil) when constructed, while still allowing arbitrary, undeclared keys to be assigned - unlike Hashie::Dash, which restricts assignment to only pre-declared properties.

@example

class PersonMash < Hashie::Mash
  include Hashie::Extensions::Mash::RequiredKeys

  required_keys :name, :email
end

expect { PersonMash.new(email: 'bob@example.com') }
  .to raise_error(ArgumentError, 'the following keys are required: `name`')

person = PersonMash.new(name: 'Bob', email: 'bob@example.com')
person.age = 42 # arbitrary, undeclared keys are still allowed
person.age # => 42

Public Class Methods

included(base) click to toggle source

@example Install required-key declarations

klass = Class.new(Hashie::Mash) do
  include Hashie::Extensions::Mash::RequiredKeys
end
klass.required_keys # => []
# File lib/hashie/extensions/mash/required_keys.rb, line 31
def self.included(base)
  base.instance_variable_set(:@required_keys, [])
  base.extend(ClassMethods)
  base.include(InstanceMethods)
end