Class: String

Inherits:
Object
  • Object
show all
Includes:
Everythingrb::StringQuotable
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

  • #to_camelcase: Convert strings to camelCase or PascalCase

Examples:

require "everythingrb/string"

'{"user": {"name": "Alice"}}'.to_ostruct.user.name  # => "Alice"
"Hello".with_quotes  # => "\"Hello\""
"hello_world".to_camelcase  # => "HelloWorld"

Instance Method Summary collapse

Methods included from Everythingrb::StringQuotable

#in_quotes

Instance Method Details

#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)

Examples:

Convert a string to PascalCase (default)

"welcome to the jungle!".to_camelcase     # => "WelcomeToTheJungle"

Convert a string to camelCase (lowercase first)

"welcome to the jungle!".to_camelcase(:lower)     # => "welcomeToTheJungle"

With mixed formatting

"please-WAIT while_loading...".to_camelcase    # => "PleaseWaitWhileLoading"

Parameters:

  • first_letter (Symbol) (defaults to: :upper)

    Whether the first letter should be uppercase (:upper) or lowercase (:lower)

Returns:

  • (String)

    The camelCased string

See Also:

  • #capitalize
  • #downcase


148
149
150
151
152
153
154
155
156
157
158
159
160
161
# File 'lib/everythingrb/string.rb', line 148

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_deep_hHash?

Note:

If nested JSON strings fail to parse, they remain as strings rather than causing the entire operation to fail

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

Examples:

nested_json = '{
  "user": "{\"name\":\"Alice\",\"roles\":[\"admin\"]}"
}'
nested_json.to_deep_h
# => {user: {name: "Alice", roles: ["admin"]}}

Returns:

  • (Hash)

    Deeply parsed hash with all nested JSON strings converted

  • (nil)

    If the string is not valid JSON at the top level



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/everythingrb/string.rb', line 57

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

Examples:

'{"name": "Alice"}'.to_h  # => {name: "Alice"}
"invalid json".to_h       # => nil

Returns:

  • (Hash, nil)

    Parsed JSON as hash or nil if invalid JSON



32
33
34
35
36
# File 'lib/everythingrb/string.rb', line 32

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

#to_istructData?

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

Examples:

'{"name": "Alice"}'.to_istruct      # => #<data name="Alice">
"not json".to_istruct               # => nil

Returns:

  • (Data, nil)

    Immutable Data structure or nil if invalid JSON



91
92
93
# File 'lib/everythingrb/string.rb', line 91

def to_istruct
  to_h&.to_istruct
end

#to_ostructOpenStruct?

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

Examples:

'{"name": "Alice"}'.to_ostruct      # => #<OpenStruct name="Alice">
"not json".to_ostruct               # => nil

Returns:

  • (OpenStruct, nil)

    OpenStruct or nil if invalid JSON



105
106
107
# File 'lib/everythingrb/string.rb', line 105

def to_ostruct
  to_h&.to_ostruct
end

#to_structStruct?

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

Examples:

'{"name": "Alice"}'.to_struct       # => #<struct name="Alice">
"not json".to_struct                # => nil

Returns:

  • (Struct, nil)

    Struct or nil if invalid JSON



119
120
121
# File 'lib/everythingrb/string.rb', line 119

def to_struct
  to_h&.to_struct
end