Module: CMDx::Coercions::Symbol

Extended by:
Symbol
Included in:
Symbol
Defined in:
lib/cmdx/coercions/symbol.rb

Overview

Coerces to Symbol via ‘#to_s.to_sym`. Fails when `value` has no `#to_s` (i.e. `BasicObject` instances) or when the resulting string exceeds MAX_LENGTH characters.

Symbols are never garbage-collected when interned from arbitrary strings, so unbounded coercion of attacker-controlled input would grow the symbol table unbounded (memory DoS). The default cap is generous for legitimate identifiers; pass ‘max_length:` to tighten it for hot paths or untrusted boundaries.

Constant Summary collapse

MAX_LENGTH =
256

Instance Method Summary collapse

Instance Method Details

#call(value, options = EMPTY_HASH) ⇒ Symbol, Coercions::Failure

Parameters:

  • value (Object)
  • options (Hash{Symbol => Object}) (defaults to: EMPTY_HASH)

Options Hash (options):

  • :max_length (Integer) — default: 256

    reject strings longer than this

Returns:



24
25
26
27
28
29
30
31
32
33
34
# File 'lib/cmdx/coercions/symbol.rb', line 24

def call(value, options = EMPTY_HASH)
  return value if value.is_a?(::Symbol)

  str   = value.to_s
  limit = options[:max_length] || MAX_LENGTH
  return coercion_failure if str.length > limit

  str.to_sym
rescue NoMethodError
  coercion_failure
end