Class: String
- Inherits:
-
Object
- Object
- String
- Includes:
- Everythingrb::StringQuotable
- Defined in:
- lib/everythingrb/string.rb
Overview
Extensions to Ruby’s core String class
Provides:
-
#parse_json: Parse JSON strings with error handling
-
#to_ostruct, #to_istruct, #to_struct: Convert JSON to data structures
-
#with_quotes, #in_quotes: Wrap strings in quotes
-
#to_camelcase: Convert strings to camelCase or PascalCase
Instance Method Summary collapse
-
#parse_json(**opts) ⇒ Hash, ...
Parses the string as JSON and returns the result.
-
#to_camelcase(first_letter = :upper) ⇒ String
Converts a string to camelCase or PascalCase.
-
#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.
Methods included from Everythingrb::StringQuotable
Instance Method Details
#parse_json(**opts) ⇒ Hash, ...
Parses the string as JSON and returns the result
Safely parses JSON with symbolized keys by default. Returns nil instead of raising an exception if the string is not valid JSON.
47 48 49 50 51 52 53 |
# File 'lib/everythingrb/string.rb', line 47 def parse_json(**opts) opts[:symbolize_names] = true unless opts.key?(:symbolize_names) JSON.parse(self, opts) rescue JSON::ParserError nil end |
#to_camelcase(first_letter = :upper) ⇒ String
Converts a string to camelCase or PascalCase
Handles strings with spaces, hyphens, underscores, and special characters.
-
Hyphens and underscores are treated like spaces
-
Special characters and symbols are removed
-
Capitalizing each word (except the first if set)
122 123 124 125 126 127 128 129 130 131 132 133 134 135 |
# File 'lib/everythingrb/string.rb', line 122 def to_camelcase(first_letter = :upper) gsub(/[-_]/, " ") # Treat dash/underscore as new words so they are capitalized .gsub(/[^a-zA-Z0-9\s]/, "") # Remove any special characters .split(/\s+/) # Split by word (removes extra whitespace) .map # Don't use `join_map(with_index: true)`, this is faster .with_index do |word, index| # Convert the words if index == 0 && first_letter == :lower word.downcase else word.capitalize end end .join # And join it back together end |
#to_istruct ⇒ Data?
Attempts to parse JSON and convert to Data struct. Returns nil if string does not contain valid JSON
65 66 67 |
# File 'lib/everythingrb/string.rb', line 65 def to_istruct parse_json&.to_istruct end |
#to_ostruct ⇒ OpenStruct?
Attempts to parse JSON and convert to OpenStruct. Returns nil if string does not contain valid JSON
79 80 81 |
# File 'lib/everythingrb/string.rb', line 79 def to_ostruct parse_json&.to_ostruct end |
#to_struct ⇒ Struct?
Attempts to parse JSON and convert to Struct. Returns nil if string does not contain valid JSON
93 94 95 |
# File 'lib/everythingrb/string.rb', line 93 def to_struct parse_json&.to_struct end |