Module: Lazier::Object

Extended by:
ActiveSupport::Concern
Defined in:
lib/lazier/object.rb

Overview

Extensions for all objects.

Constant Summary

BOOLEAN_MATCHER =

Expression to match a boolean value.

/^(\s*(1|0|true|false|yes|no|t|f|y|n)\s*)$/i
BOOLEAN_TRUE_MATCHER =

Expression to match a true value.

/^(\s*(1|true|yes|t|y)\s*)$/i
INTEGER_MATCHER =

Expression to match a integer value.

/^([+-]?)(\d+)$/
FLOAT_MATCHER =

Expression to match a float value.

/^([+-]?)(\d+)([.,]\d+)?$/

Instance Method Summary (collapse)

Instance Method Details

- (Boolean) boolean?

Checks if the object is a valid boolean value.

Returns:

  • (Boolean)

    true is a valid boolean value, false otherwise.



54
55
56
# File 'lib/lazier/object.rb', line 54

def boolean?
  nil? || is_a?(::TrueClass) || is_a?(::FalseClass) || to_s =~ ::Lazier::Object::BOOLEAN_MATCHER
end

- (String) ensure(default, verifier = :blank?)

Makes sure that the object is set to something meaningful.

Parameters:

  • default (String)

    The default value to return if the verifier or the block returns true.

  • verifier (Symbol) (defaults to: :blank?)

    The method used to verify if the object is NOT meaningful. Ignored if a block is passed.

Returns:

  • (String)

    The current object or the default_value.



75
76
77
78
# File 'lib/lazier/object.rb', line 75

def ensure(default, verifier = :blank?)
  valid = block_given? ? yield(self) : send(verifier)
  !valid ? self : default
end

- (Array) ensure_array(default: nil, no_duplicates: false, compact: false, flatten: false, sanitizer: nil, &block)

Makes sure that the object is an array. For non array objects, return a single element array containing the object.

Parameters:

  • default (Array|NilClass)

    The default array to use. If not specified, an array containing the object is returned.

  • no_duplicates (Boolean)

    If to remove duplicates from the array before sanitizing.

  • compact (Boolean)

    If to compact the array before sanitizing.

  • flatten (Boolean)

    If to flatten the array before sanitizing.

  • sanitizer (Symbol|nil)

    If not nil, the method to use to sanitize entries of the array. Ignored if a block is present.

  • block (Proc)

    A block to sanitize entries. It must accept the value as unique argument.

Returns:

  • (Array)

    If the object is an array, then the object itself, a single element array containing the object otherwise.



102
103
104
105
106
107
108
109
110
111
112
# File 'lib/lazier/object.rb', line 102

def ensure_array(default: nil, no_duplicates: false, compact: false, flatten: false, sanitizer: nil, &block)
  rv =
    if is_a?(::Array)
      self
    else
      default || [self].compact
    end

  rv = manipulate_array(rv, no_duplicates, compact, flatten).map(&(block || sanitizer)) if block_given? || sanitizer
  manipulate_array(rv, no_duplicates, compact, flatten)
end

- (Hash) ensure_hash(accesses: nil, default: {}, sanitizer: nil, &block)

Makes sure that the object is an hash. For non hash objects, return an hash basing on the default_value parameter.

Parameters:

  • accesses (Symbol|NilClass|Array)

    The requested access for the keys of the returned object.

  • default (Hash|String|Symbol|NilClass)

    The default value to use. If it is an Hash, it is returned as value otherwise it is used to build as a key to build an hash with the current object as only value (everything but strings and symbols are mapped to key). Passing nil is equal to pass an empty Hash.

  • sanitizer (Symbol|nil)

    If not nil, the method to use to sanitize values of the hash. Ignored if block is present.

  • block (Proc)

    A block to sanitize entries. It must accept the value as unique argument.

Returns:

  • (Hash)

    If the object is an hash, then the object itself, a hash with the object as single value otherwise.

See Also:



125
126
127
128
129
130
# File 'lib/lazier/object.rb', line 125

def ensure_hash(accesses: nil, default: {}, sanitizer: nil, &block)
  rv = convert_to_hash(default)
  rv = sanitize_hash(rv, sanitizer, block) if block || sanitizer

  rv.respond_to?(:ensure_access) ? rv.ensure_access(accesses.ensure_array) : rv
end

- (String) ensure_string(default = "", conversion_method = :to_s)

Makes sure that the object is a string.

Parameters:

  • default (String) (defaults to: "")

    The default value to return if the object is nil. It is also passed to the block stringifier.

  • conversion_method (Symbol) (defaults to: :to_s)

    The method used to convert the object to a string. Ignored if a block is passed.

Returns:

  • (String)

    The string representation of the object.



85
86
87
88
89
90
91
# File 'lib/lazier/object.rb', line 85

def ensure_string(default = "", conversion_method = :to_s)
  if is_a?(NilClass)
    default
  else
    block_given? ? yield(self, default) : send(conversion_method)
  end
end

- (Boolean) float?

Checks if the object is a valid float.

Returns:

  • (Boolean)

    true is a valid float, false otherwise.



47
48
49
# File 'lib/lazier/object.rb', line 47

def float?
  number?(Numeric, ::Lazier::Object::FLOAT_MATCHER)
end

- (String) format_boolean(true_name: nil, false_name: nil)

Formats a boolean.

Parameters:

  • true_name (String)

    The string representation of true. Defaults to Yes.

  • false_name (String)

    The string representation of false. Defaults to No.

Returns:

  • (String)

    The string representation of the object.

See Also:



212
213
214
215
# File 'lib/lazier/object.rb', line 212

def format_boolean(true_name: nil, false_name: nil)
  settings = ::Lazier.settings.boolean_names
  to_boolean ? (true_name || settings[true]) : (false_name || settings[false])
end

- (String) format_number(precision: nil, decimal_separator: nil, add_string: nil, k_separator: nil)

Formats a number.

Parameters:

  • precision (Fixnum)

    The precision to show.

  • decimal_separator (String)

    The string to use as decimal separator.

  • add_string (String)

    The string to append to the number.

  • k_separator (String)

    The string to use as thousands separator.

Returns:

  • (String)

    The string representation of the object.

See Also:



192
193
194
195
196
197
198
199
200
201
202
203
204
# File 'lib/lazier/object.rb', line 192

def format_number(precision: nil, decimal_separator: nil, add_string: nil, k_separator: nil)
  if number?
    settings = ::Lazier.settings.format_number
    add_string ||= settings[:add_string]

    rv = format("%0.#{[precision || settings[:precision], 0].max}f", to_float).split(".")
    rv[0].gsub!(/(\d)(?=(\d{3})+(?!\d))/, "\\1#{k_separator || settings[:k_separator]}")
    rv = rv.join(decimal_separator || settings[:decimal_separator])
    add_string ? rv + " #{add_string}" : rv
  else
    nil
  end
end

- (String) indexize(length: 2, filler: "0", formatter: :rjust)

Prepares an object to be printed in list summaries, like [01/04] Opening this....

Parameters:

  • length (Fixnum)

    The minimum length of the label.

  • filler (String)

    The minimum length of the label.

  • formatter (Symbol)

    The method to use to format the label. Must accept the length and the `filler arguments.

Returns:

  • (String)

    The object inspected and formatted.



223
224
225
# File 'lib/lazier/object.rb', line 223

def indexize(length: 2, filler: "0", formatter: :rjust)
  ensure_string.send(formatter, length, filler)
end

- (Boolean) integer?

Checks if the object is a valid integer.

Returns:

  • (Boolean)

    true is a valid integer, false otherwise.



40
41
42
# File 'lib/lazier/object.rb', line 40

def integer?
  number?(Integer, ::Lazier::Object::INTEGER_MATCHER)
end

- (String) normalize_number

Normalizes a number for conversion. Basically this methods removes all separator and ensures that . is used for decimal separator.

Returns:

  • (String)

    The normalized number.



26
27
28
# File 'lib/lazier/object.rb', line 26

def normalize_number
  boolean? ? to_i.to_s : ensure_string.strip.gsub(/[\.,](?=(.*[\.,]))/, "").gsub(",", ".")
end

- (Boolean) number?(klass = Integer, matcher = ::Lazier::Object::FLOAT_MATCHER)

Checks if the object is of a numeric class of matches a numeric string expression.

Returns:

  • (Boolean)

    true is a valid numeric object, false otherwise.



33
34
35
# File 'lib/lazier/object.rb', line 33

def number?(klass = Integer, matcher = ::Lazier::Object::FLOAT_MATCHER)
  nil? || is_a?(klass) || boolean? || normalize_number =~ matcher
end

- (Float) round_to_precision(precision = 2)

Returns the rounded float representaton of the object.

Parameters:

  • precision (Fixnum) (defaults to: 2)

    The precision to keep.

Returns:

  • (Float)

    The rounded float representaton of the object.



180
181
182
# File 'lib/lazier/object.rb', line 180

def round_to_precision(precision = 2)
  number? ? to_float.round([precision, 0].max) : nil
end

- (Object|nil) safe_send(method, *args, &block)

Sends a method to the object. If the objects doesn’t not respond to the method, it returns nil instead of raising an exception.

Parameters:

  • method (Symbol)

    The method to send.

  • args (Array)

    The arguments to send.

  • block (Proc)

    The block to pass to the method.

Returns:

  • (Object|nil)

    The return value of the method or nil, if the object does not respond to the method.



64
65
66
67
68
# File 'lib/lazier/object.rb', line 64

def safe_send(method, *args, &block)
  send(method, *args, &block)
rescue NoMethodError
  nil
end

- (Boolean) to_boolean

Converts the object to a boolean.

Returns:

  • (Boolean)

    The boolean representation of the object.



135
136
137
# File 'lib/lazier/object.rb', line 135

def to_boolean
  is_a?(TrueClass) || to_integer == 1 || ::Lazier::Object::BOOLEAN_TRUE_MATCHER.match(ensure_string).is_a?(MatchData)
end

- (String) to_debug(format: :pretty_json, as_exception: true)

Inspects an object.

Parameters:

  • format

    The format to use. If different from :pretty_json, the object must respond to the to_#{format} method.

  • as_exception (Boolean)

    If raise an exception.

Returns:

  • (String)

    The object inspected and formatted.



171
172
173
174
# File 'lib/lazier/object.rb', line 171

def to_debug(format: :pretty_json, as_exception: true)
  rv = send("to_#{format}")
  as_exception ? raise(::Lazier::Exceptions::Debug, rv) : rv
end

- (Float) to_float(default = 0.0)

Converts the object to a float.

Parameters:

  • default (Float) (defaults to: 0.0)

    The value to return if the conversion is not possible.

Returns:

  • (Float)

    The float representation of the object.



151
152
153
154
155
156
157
# File 'lib/lazier/object.rb', line 151

def to_float(default = 0.0)
  if float?
    ::Kernel.Float(is_a?(::Numeric) ? self : normalize_number)
  else
    default
  end
end

- (Fixnum) to_integer(default = 0)

Converts the object to a integer.

Parameters:

  • default (Fixnum) (defaults to: 0)

    The value to return if the conversion is not possible.

Returns:

  • (Fixnum)

    The integer representation of the object.



143
144
145
# File 'lib/lazier/object.rb', line 143

def to_integer(default = 0)
  to_float(default).to_i
end

- (String) to_pretty_json

Converts an object to a pretty formatted JSON string.

Returns:

  • (String)

    The object as a pretty JSON string.



162
163
164
# File 'lib/lazier/object.rb', line 162

def to_pretty_json
  Lazier.platform != :java ? Oj.dump(self, mode: :compat, indent: 2) : ::JSON.pretty_generate(self)
end