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:

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

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

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

Examples:

Basic usage

'{"name": "Alice"}'.parse_json  # => {name: "Alice"}

With nested data

'{"user": {"roles": ["admin"]}}'.parse_json
# => {user: {roles: ["admin"]}}

Invalid JSON returns nil

"not json".parse_json  # => nil

Disable symbolized keys

'{"name": "Alice"}'.parse_json(symbolize_names: false)
# => {"name" => "Alice"}

Parameters:

  • opts (Hash)

    Options to pass to JSON.parse

Options Hash (**opts):

  • :symbolize_names (Boolean) — default: true

    Whether to symbolize keys

Returns:

  • (Hash, Array, nil)

    Parsed JSON or nil if invalid



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)

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


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_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



65
66
67
# File 'lib/everythingrb/string.rb', line 65

def to_istruct
  parse_json&.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



79
80
81
# File 'lib/everythingrb/string.rb', line 79

def to_ostruct
  parse_json&.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



93
94
95
# File 'lib/everythingrb/string.rb', line 93

def to_struct
  parse_json&.to_struct
end