Method: Sinclair::Caster::ClassMethods#cast
- Defined in:
- lib/sinclair/caster/class_methods.rb
#cast(value, key, **opts) ⇒ Object #cast(value, class_key, **opts) ⇒ Object
Cast a value using the registered caster
Overloads:
-
#cast(value, key, **opts) ⇒ Object
Examples:
Casts with a symbol key
# math_caster.rb class MathCaster < Sinclair::Caster cast_with(:float, :to_f) cast_with(:log) do |value, base: 10| value = MathCaster.cast(value, :float) Math.log(value, base) end cast_with(:exp) do |value, base: 10| value = MathCaster.cast(value, :float) base**value end end # main.rb initial = Random.rand(10..20) log = MathCaster.cast(initial, :log) exp = MathCaster.cast(log, :exp) # exp will be betwween initial - 0.0001 and initial + 0.0001Casts passing parameter
base = Random.rand(3..6) initial = Random.rand(10..20) log = MathCaster.cast(initial, :log, base: base) exp = MathCaster.cast(log, :exp, base: base) # exp will be betwween initial - 0.0001 and initial + 0.0001Parameters:
-
value to be cast
-
key where the caster is registered under
-
Options to be sent to the caster
-
-
#cast(value, class_key, **opts) ⇒ Object
When the
class_keydoes not match the stored key, but matches a superclass, the registerd caster is returned.Examples:
Casts with class key
# ruby_string_caster.rb class RubyStringCaster < Sinclair::Caster master_caster! cast_with(NilClass) { 'nil' } cast_with(Symbol) { |value| ":#{value}" } cast_with(String, :to_json) cast_with(Object, :to_s) def self.to_ruby_string(value) cast(value, value.class) end end # main.rb hash = { a: 1, b: 2, 'c' => nil } string = 'my string' symbol = :the_symbol number = 10 null = nil " hash_value = \#{RubyStringCaster.to_ruby_string(hash)}\n string_value = \#{RubyStringCaster.to_ruby_string(string)}\n symbol_value = \#{RubyStringCaster.to_ruby_string(symbol)}\n number = \#{RubyStringCaster.to_ruby_string(number)}\n null_value = \#{RubyStringCaster.to_ruby_string(null)}\n" # Generates the String # # <<-RUBY # hash_value = {:a=>1, :b=>2, "c"=>nil} # string_value = "my string" # symbol_value = :the_symbol # number = 10 # null_value = nil # RUBYParameters:
-
value to be cast
-
Class to used as key in the casters storage
-
Options to be sent to the caster
-
Returns:
-
the value cast
See Also:
API:
-
public
25 26 27 |
# File 'lib/sinclair/caster/class_methods.rb', line 25 def cast(value, key, **) caster_for(key).cast(value, **) end |