Class: String

Inherits:
Object
  • Object
show all
Defined in:
lib/everythingrb/core/string.rb

Instance Method Summary collapse

Instance Method Details

#to_deep_hHash

Deep parsing of nested JSON strings Recursively attempts to parse string values as JSON

Returns:

  • (Hash)

    Deeply parsed hash



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/everythingrb/core/string.rb', line 23

def to_deep_h
  recursive_convert = lambda do |object|
    case object
    when Array
      object.map { |v| recursive_convert.call(v) }
    when String
      result = object.to_deep_h

      # Nested JSON
      if result.is_a?(Array) || result.is_a?(Hash)
        recursive_convert.call(result)
      else
        object
      end
    when Hash
      object.transform_values { |v| recursive_convert.call(v) }
    else
      object
    end
  end

  recursive_convert.call(to_h)
end

#to_hHash? Also known as: to_a

Converts JSON string to Hash, returning nil if it failed

Returns:

  • (Hash, nil)

    Parsed JSON as hash



9
10
11
12
13
# File 'lib/everythingrb/core/string.rb', line 9

def to_h
  JSON.parse(self, symbolize_names: true)
rescue JSON::ParserError
  nil
end

#to_istructnil, Data

Attempts to parse JSON and convert to Data struct. Returns nil if string does not contain valid JSON

Returns:

  • (nil, Data)


53
54
55
# File 'lib/everythingrb/core/string.rb', line 53

def to_istruct
  to_h&.to_istruct
end

#to_ostructnil, OpenStruct

Attempts to parse JSON and convert to OpenStruct. Returns nil if string does not contain valid JSON

Returns:



62
63
64
# File 'lib/everythingrb/core/string.rb', line 62

def to_ostruct
  to_h&.to_ostruct
end

#to_structnil, Struct

Attempts to parse JSON and convert to Struct. Returns nil if string does not contain valid JSON

Returns:

  • (nil, Struct)


72
73
74
# File 'lib/everythingrb/core/string.rb', line 72

def to_struct
  to_h&.to_struct
end

#with_quotesString Also known as: in_quotes

Returns self wrapped in double quotes.

Returns:



81
82
83
# File 'lib/everythingrb/core/string.rb', line 81

def with_quotes
  %("#{self}")
end