|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require 'json' unless defined?(JSON::JSON_LOADED) && JSON::JSON_LOADED |
| 4 | + |
| 5 | +class Enumerator |
| 6 | + class ArithmeticSequence |
| 7 | + # See #as_json. |
| 8 | + def self.json_create(object) |
| 9 | + Range.new(*object.values_at('b', 'e', 'x')) % object['s'] |
| 10 | + end |
| 11 | + |
| 12 | + # Methods <tt>Enumerator::ArithmeticSequence#as_json</tt> and |
| 13 | + # +Enumerator::ArithmeticSequence.json_create+ can be used to serialize and |
| 14 | + # deserialize an \ArithmeticSequence object. See Marshal[rdoc-ref:Marshal]. |
| 15 | + # |
| 16 | + # \Method <tt>Enumerator::ArithmeticSequence#as_json</tt> serializes +self+, |
| 17 | + # returning a 5-element hash representing +self+: |
| 18 | + # |
| 19 | + # require 'json/add/arithmetic_sequence' |
| 20 | + # |
| 21 | + # x = 42.step(by: 3, to: 72).as_json |
| 22 | + # # => {"json_class"=>"Enumerator::ArithmeticSequence", "b"=>42, "e"=>72, "x"=>false, "s"=>3} |
| 23 | + # |
| 24 | + # y = ((42...72) % 4).as_json |
| 25 | + # # => {"json_class"=>"Enumerator::ArithmeticSequence", "b"=>42, "e"=>72, "x"=>true, "s"=>4} |
| 26 | + # |
| 27 | + # \Method +JSON.create+ deserializes such a hash, returning an |
| 28 | + # \ArithmeticSequence object: |
| 29 | + # |
| 30 | + # Enumerator::ArithmeticSequence.json_create(x) # => ((42..72).%(3)) |
| 31 | + # Enumerator::ArithmeticSequence.json_create(y) # => ((42...72).%(4)) |
| 32 | + # |
| 33 | + def as_json(*) |
| 34 | + { |
| 35 | + JSON.create_id => self.class.name, |
| 36 | + 'b' => self.begin, |
| 37 | + 'e' => self.end, |
| 38 | + 'x' => exclude_end?, |
| 39 | + 's' => step |
| 40 | + } |
| 41 | + end |
| 42 | + |
| 43 | + # Returns a JSON string representing +self+: |
| 44 | + # |
| 45 | + # require 'json/add/arithmetic_sequence' |
| 46 | + # |
| 47 | + # puts 42.step(by: 3, to: 72).to_json |
| 48 | + # puts ((42...72) % 4).to_json |
| 49 | + # |
| 50 | + # Output: |
| 51 | + # |
| 52 | + # {"json_class":"Enumerator::ArithmeticSequence","b":42,"e":72,"x":false,"s":3} |
| 53 | + # {"json_class":"Enumerator::ArithmeticSequence","b":42,"e":72,"x":true,"s":4} |
| 54 | + # |
| 55 | + def to_json(*) = as_json.to_json(*) |
| 56 | + end |
| 57 | +end |
0 commit comments