Module: Foraneus::Utils
- Defined in:
- lib/foraneus/utils.rb
Class Method Summary collapse
-
.fetch(hash, key) ⇒ Object, Boolean
Return the value of a key in the given hash and flag indicating whether the keys exists or not.
- .nested_converter?(converter) ⇒ Boolean
-
.parse_datum(field, s, converter) ⇒ Object, ...
Parses a raw value.
-
.raw_datum(v, converter) ⇒ String
Obtains a raw representation of a value and assigns it to the corresponding field.
-
.singleton_attr_accessor(instance, attribute, initial_value = nil) ⇒ Object
Creates a singleton attribute accessor on an instance.
Class Method Details
.fetch(hash, key) ⇒ Object, Boolean
Return the value of a key in the given hash and flag indicating whether the keys exists or not
If the given key is not present then tries fetching key#to_sym
12 13 14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/foraneus/utils.rb', line 12 def self.fetch(hash, key) v = nil is_present = true v = hash.fetch(key) do hash.fetch(key.to_sym) do is_present = false nil end end [v, is_present] end |
.nested_converter?(converter) ⇒ Boolean
70 71 72 |
# File 'lib/foraneus/utils.rb', line 70 def self.nested_converter?(converter) Class === converter && converter.ancestors.include?(Foraneus) end |
.parse_datum(field, s, converter) ⇒ Object, ...
Parses a raw value.
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
# File 'lib/foraneus/utils.rb', line 36 def self.parse_datum(field, s, converter) if s == '' && converter.opts.fetch(:blanks_as_nil, true) s = nil end if s.nil? && converter.opts[:required] raise KeyError, "required parameter not found: #{field.inspect}" end result = if s.nil? converter.opts[:default] else converter.parse(s) end [result, nil] rescue error = Foraneus::Error.new($!.class.name, $!.) [nil, error] end |
.raw_datum(v, converter) ⇒ String
Obtains a raw representation of a value and assigns it to the corresponding field.
66 67 68 |
# File 'lib/foraneus/utils.rb', line 66 def self.raw_datum(v, converter) converter.raw(v) unless v.nil? end |
.singleton_attr_accessor(instance, attribute, initial_value = nil) ⇒ Object
Creates a singleton attribute accessor on an instance.
79 80 81 82 83 84 85 86 87 |
# File 'lib/foraneus/utils.rb', line 79 def self.singleton_attr_accessor(instance, attribute, initial_value = nil) spec = instance.class instance.singleton_class.send(:attr_accessor, spec.accessors[attribute]) instance.instance_exec do instance.instance_variable_set(:"@#{spec.accessors[attribute]}", initial_value) end end |