Class: RichString

Inherits:
Object
  • Object
show all
Defined in:
lib/brut/junk_drawer.rb

Overview

A wrapper around a string to avoid adding a ton of methods to String.

This may not survive to 1.0 - use at your own risk.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(string) ⇒ RichString

Create a RichString. This calls to_s on its argument.

Parameters:

  • string (String|Object)

    the string to wrap. to_s is called, so be sure that's what you want.



77
78
79
# File 'lib/brut/junk_drawer.rb', line 77

def initialize(string)
  @string = string.to_s
end

Class Method Details

.from_string(string, blank_is_nil: true) ⇒ RichString|nil

Create a RichString, return nil instead for blank strings or nil

Parameters:

  • string (String|nil)

    the string to convert.

  • blank_is_nil (true|false) (defaults to: true)

    if true, a blank string or nil is considered nil and nil is returned.

Returns:

  • (RichString|nil)

    a RichString containing the string or nil if the string is blank or nil, accounting for blank_is_nil:



63
64
65
66
67
68
69
70
71
# File 'lib/brut/junk_drawer.rb', line 63

def self.from_string(string,blank_is_nil:true)
  if string.nil?
      return nil
  end
  if string.to_s.strip == "" && blank_is_nil
    return nil
  end
  self.new(string)
end

Instance Method Details

#+(other) ⇒ Object



168
169
170
171
172
173
174
175
176
# File 'lib/brut/junk_drawer.rb', line 168

def +(other)
  if other.kind_of?(RichString)
    RichString.new(self.to_s + other.to_s)
  elsif other.kind_of?(String)
    self.to_s + other
  else
    super(other)
  end
end

#<=>(other) ⇒ Object



158
159
160
161
162
163
164
165
166
# File 'lib/brut/junk_drawer.rb', line 158

def <=>(other)
  if other.kind_of?(RichString)
    self.to_s <=> other.to_s
  elsif other.kind_of?(String)
    self.to_s <=> other
  else
    super
  end
end

#==(other) ⇒ Object



148
149
150
151
152
153
154
155
156
# File 'lib/brut/junk_drawer.rb', line 148

def ==(other)
  if other.kind_of?(RichString)
    self.to_s == other.to_s
  elsif other.kind_of?(String)
    self.to_s == other
  else
    false
  end
end

#lengthObject



144
# File 'lib/brut/junk_drawer.rb', line 144

def length = to_s.length

#to_sObject



142
# File 'lib/brut/junk_drawer.rb', line 142

def to_s = @string

#to_s_or_nilObject



146
# File 'lib/brut/junk_drawer.rb', line 146

def to_s_or_nil = @string.to_s.strip.empty? ? nil : self.to_s

#to_strObject



143
# File 'lib/brut/junk_drawer.rb', line 143

def to_str = self.to_s