Class: String
- Inherits:
-
Object
- Object
- String
- Defined in:
- lib/everythingrb/string.rb
Overview
Extensions to Ruby’s core String class
Provides:
-
#to_h, #to_a: Convert JSON strings to Hash/Array with error handling
-
#to_deep_h: Recursively parse nested JSON strings
-
#to_ostruct, #to_istruct, #to_struct: Convert JSON to data structures
-
#with_quotes, #in_quotes: Wrap strings in quotes
Instance Method Summary collapse
-
#to_deep_h ⇒ Hash
Deep parsing of nested JSON strings Recursively attempts to parse string values as JSON.
-
#to_h ⇒ Hash?
(also: #to_a)
Converts JSON string to Hash, returning nil if it failed.
-
#to_istruct ⇒ Data?
Attempts to parse JSON and convert to Data struct.
-
#to_ostruct ⇒ OpenStruct?
Attempts to parse JSON and convert to OpenStruct.
-
#to_struct ⇒ Struct?
Attempts to parse JSON and convert to Struct.
-
#with_quotes ⇒ String
(also: #in_quotes)
Returns self wrapped in double quotes.
Instance Method Details
#to_deep_h ⇒ Hash
Deep parsing of nested JSON strings Recursively attempts to parse string values as JSON
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 |
# File 'lib/everythingrb/string.rb', line 49 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_h ⇒ Hash? Also known as: to_a
Converts JSON string to Hash, returning nil if it failed
28 29 30 31 32 |
# File 'lib/everythingrb/string.rb', line 28 def to_h JSON.parse(self, symbolize_names: true) rescue JSON::ParserError nil end |
#to_istruct ⇒ Data?
Attempts to parse JSON and convert to Data struct. Returns nil if string does not contain valid JSON
83 84 85 |
# File 'lib/everythingrb/string.rb', line 83 def to_istruct to_h&.to_istruct end |
#to_ostruct ⇒ OpenStruct?
Attempts to parse JSON and convert to OpenStruct. Returns nil if string does not contain valid JSON
97 98 99 |
# File 'lib/everythingrb/string.rb', line 97 def to_ostruct to_h&.to_ostruct end |
#to_struct ⇒ Struct?
Attempts to parse JSON and convert to Struct. Returns nil if string does not contain valid JSON
111 112 113 |
# File 'lib/everythingrb/string.rb', line 111 def to_struct to_h&.to_struct end |
#with_quotes ⇒ String Also known as: in_quotes
Returns self wrapped in double quotes
124 125 126 |
# File 'lib/everythingrb/string.rb', line 124 def with_quotes %("#{self}") end |