Module: Mangrove::TryFromExt
- Extended by:
- T::Helpers, T::Sig
- Includes:
- Kernel
- Defined in:
- lib/mangrove/try_from_ext.rb
Instance Method Summary collapse
Instance Method Details
#try_convert_from(from:, to:, err:, &block) ⇒ void
This method returns an undefined value.
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
# File 'lib/mangrove/try_from_ext.rb', line 21 def try_convert_from(from:, to:, err:, &block) T.bind(self, T::Class[T.type_parameter(:O)]) vars = from.instance_variable_get(:@convertable_to) || {} vars[self] = block from.instance_variable_set(:@convertable_to, vars) @convertable_from ||= {} @convertable_from[from] = [err, block] into_t = T.cast(self, Class) from.define_method("try_into_#{T.must_because(into_t.name) { "name is required" }.gsub(/::|([A-Z]+)([A-Z][a-z])/, '\1_\2').gsub(/([a-z\d])([A-Z])/, '\1_\2').downcase}") do proc = T.unsafe(self).class.ancestors.lazy.map { |klass| klass.instance_variable_get(:@convertable_to)&.[](into_t) }.find(&:itself) proc.call(self) end end |