ValidateOptions
This is a tiny Ruby snippet that provides a smarter way to validate ‘options’-like hashes (a.k.a. named arguments).
For example:
require 'validate_options'
def foo(text, = {})
# Only :align and :color are allowed.
, :align, :color
text
end
# Disabled by default.
ValidateOptions.enable!
foo("Hello")
# => "Hello"
foo("Hello", :align => :left)
# => "Hello"
foo("Hello", :colour => :red)
# ArgumentError: Invalid options provided: :colour.
Using a block for more fine-grained control over arguments:
def (text, = {})
, :align do |op|
raise ":align should be either :left or :right" if op[:align] && ![:left, :right].include?(op[:align])
end
end
("Hello", :align => :left)
# => "Hello"
("Hello", :align => :center)
# ArgumentError: :align should be either :left or :right
Valid options can also be specified outside the method:
class Formatter
def print(text, = {})
puts text
end
:print, :align, :color
end
Formatter.new.print("Hello")
# => "Hello"
Formatter.new.print("Hello", :align => :left)
# => "Hello"
Formatter.new.print("Hello", :colour => :red)
# ArgumentError: Invalid options provided: :colour.