Class: Plumb::Codec::RangeEncoder

Inherits:
Object
  • Object
show all
Defined in:
lib/plumb/codec.rb

Overview

Range <=> a JSON object { from:, to:, exclusive: }. Generic over the range's member type: it matches ANY Range[member] (its output type is the Range top), and #input_type_for builds the input from the matched member — so a Range[Date] serializes its endpoints as ISO strings, a Range[Integer] as JSON numbers, etc., because the codec rewrites those member-typed from/to fields through itself. from/to are nullable for beginless/endless ranges; exclusive records whether the end is excluded (1...5 vs 1..5).

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.input_type_for(matched) ⇒ Object

Specialize the input to the matched range's member type. A non-Range match (should not happen — only RangeClass is a subtype of the Range top) falls back to the generic declared input.



691
692
693
694
695
696
697
698
699
700
# File 'lib/plumb/codec.rb', line 691

def self.input_type_for(matched)
  return input_type unless matched.is_a?(Plumb::RangeClass)

  member = matched.children.first
  Types::Hash[
    from: member.nullable,
    to: member.nullable,
    exclusive: Types::Boolean
  ]
end

Instance Method Details

#decode(hash) ⇒ Object



706
707
708
# File 'lib/plumb/codec.rb', line 706

def decode(hash)
  ::Range.new(hash[:from], hash[:to], hash[:exclusive])
end

#encode(range) ⇒ Object



702
703
704
# File 'lib/plumb/codec.rb', line 702

def encode(range)
  { from: range.begin, to: range.end, exclusive: range.exclude_end? }
end