Class: Args
- Inherits:
-
Object
- Object
- Args
- Defined in:
- app/args.rb
Overview
Argument validation.
Class Method Summary collapse
- .fetch_non_empty_hash(hash, key) ⇒ Object
- .fetch_non_empty_int(hash, key) ⇒ Object
- .fetch_non_empty_string(hash, key) ⇒ Object
- .fetch_non_nil(hash, key, *classes) ⇒ Object
- .fetch_optional(hash, key, *classes) ⇒ Object
- .fetch_optional_array(hash, key) ⇒ Object
- .fetch_optional_hash(hash, key) ⇒ Object
Class Method Details
.fetch_non_empty_hash(hash, key) ⇒ Object
16 17 18 19 20 21 |
# File 'app/args.rb', line 16 def self.fetch_non_empty_hash(hash, key) value = fetch_non_nil(hash, key, Hash) raise ArgumentError, "parameter #{key} empty" if value.empty? value end |
.fetch_non_empty_int(hash, key) ⇒ Object
12 13 14 |
# File 'app/args.rb', line 12 def self.fetch_non_empty_int(hash, key) fetch_non_nil(hash, key, Integer) end |
.fetch_non_empty_string(hash, key) ⇒ Object
5 6 7 8 9 10 |
# File 'app/args.rb', line 5 def self.fetch_non_empty_string(hash, key) value = fetch_non_nil(hash, key, String) raise ArgumentError, "parameter #{key} empty" if value.strip.empty? value end |
.fetch_non_nil(hash, key, *classes) ⇒ Object
31 32 33 34 35 36 37 |
# File 'app/args.rb', line 31 def self.fetch_non_nil(hash, key, *classes) raise ArgumentError, "parameter #{key} missing" unless hash.key?(key) raise ArgumentError, "parameter #{key} null" if hash[key].nil? fetch_optional(hash, key, *classes) end |
.fetch_optional(hash, key, *classes) ⇒ Object
39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'app/args.rb', line 39 def self.fetch_optional(hash, key, *classes) value = hash[key] if value && classes.size.positive? && !classes.find { |clazz| value.is_a?(clazz) } if classes.size != 1 raise ArgumentError, "parameter #{key} not #{classes.map(&:to_s).map(&:downcase).join(' or ')}" end class_name = classes[0].to_s.downcase class_name = %w[a e i o u].include?(class_name[0]) ? "an #{class_name}" : "a #{class_name}" raise ArgumentError, "parameter #{key} not #{class_name}" end value end |
.fetch_optional_array(hash, key) ⇒ Object
27 28 29 |
# File 'app/args.rb', line 27 def self.fetch_optional_array(hash, key) fetch_optional(hash, key, Array) end |
.fetch_optional_hash(hash, key) ⇒ Object
23 24 25 |
# File 'app/args.rb', line 23 def self.fetch_optional_hash(hash, key) fetch_optional(hash, key, Hash) end |