Module: M3u8::Serializable

Overview

Serializable provides a Hash representation of an item by converting its instance variables into JSON-compatible values.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.serialize(value) ⇒ Object

Recursively convert a value into a JSON-compatible form.

Parameters:

  • value (Object)

    value to convert

Returns:

  • (Object)


32
33
34
35
36
37
38
39
40
41
# File 'lib/m3u8/serializable.rb', line 32

def self.serialize(value)
  case value
  when TimeItem then serialize(value.time)
  when Time then value.iso8601
  when BigDecimal then value.to_f
  when Serializable then value.to_h
  when Hash then value.transform_values { |item| serialize(item) }
  else value
  end
end

Instance Method Details

#as_jsonHash

Convert the item into a JSON-ready Hash (alias of #to_h).

Returns:

  • (Hash)


18
19
20
# File 'lib/m3u8/serializable.rb', line 18

def as_json(*)
  to_h
end

#to_hHash<Symbol, Object>

Convert the item into a Hash of its attributes.

Returns:

  • (Hash<Symbol, Object>)


9
10
11
12
13
14
# File 'lib/m3u8/serializable.rb', line 9

def to_h
  instance_variables.each_with_object({}) do |ivar, result|
    key = ivar.to_s.delete_prefix('@').to_sym
    result[key] = Serializable.serialize(instance_variable_get(ivar))
  end
end

#to_json(*args) ⇒ String

Render the item as a JSON string.

Returns:

  • (String)


24
25
26
27
# File 'lib/m3u8/serializable.rb', line 24

def to_json(*args)
  require 'json'
  to_h.to_json(*args)
end