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_datum, #to_struct: Convert JSON to data structures (#to_istruct is deprecated, use #to_datum)
  • #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


143
144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/everythingrb/string.rb', line 143

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

Attempts to parse JSON and convert to an immutable Datum. Returns nil if string does not contain valid JSON

Examples:

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

Returns:

  • (Datum, nil)

    Immutable object or nil if invalid JSON



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

def to_datum
  parse_json&.to_datum
end

#to_istructDatum?

Deprecated.

Use #to_datum instead. Will be removed in v2.0.0.

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:

  • (Datum, nil)

    Immutable object or nil if invalid JSON



81
82
83
84
85
86
87
88
# File 'lib/everythingrb/string.rb', line 81

def to_istruct
  Everythingrb.deprecator.warn(
    "String#to_istruct is deprecated and will be removed in v2.0.0. " \
    "Use String#to_datum instead."
  )

  parse_json&.to_datum
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



100
101
102
# File 'lib/everythingrb/string.rb', line 100

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



114
115
116
# File 'lib/everythingrb/string.rb', line 114

def to_struct
  parse_json&.to_struct
end