Better way to validates a hash parameter in a method on Ruby? -


is there better dry way validate parameter hash contains key this?

module exemple   def foo_method(config)   validate_config(config)    foo = config[:foo]   bar = config[:bar]   qux = config[:qux] || {}   end   private   def validate_config(config)   raise(argumenterror, "no foo config found", caller) unless config.has_key?(:foo)   raise(argumenterror, "no bar config found", caller) unless config.has_key?(:bar)  end  end 

use hash#fetch:

def foo_method(config)   foo = config.fetch(:foo)   bar = config.fetch(:bar)   qux = config.fetch(:qux, {}) end  foo_method({})               #=> key not found: :foo (keyerror) foo_method({foo: 1})         #=> key not found: :bar (keyerror) foo_method({foo: 1, bar: 2}) #=> no error 

you can pass block fetch called if given key not found, e.g.:

  foo = config.fetch(:foo) { raise argumenterror, "no foo config found" } 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -