Module: Lazier::Object

Extended by:
ActiveSupport::Concern
Includes:
ActionView::Helpers::NumberHelper
Defined in:
lib/lazier/object.rb

Overview

Extensions for all objects.

Constant Summary collapse

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

#ensure(default_value, verifier = :blank?) ⇒ String

Makes sure that the object is set to something meaningful.

Parameters:

  • default_value (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.



59
60
61
62
# File 'lib/lazier/object.rb', line 59

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

#ensure_array(default_value = nil, uniq = false, compact = false, flatten = false, sanitizer = nil, &block) ⇒ Array

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

Parameters:

  • default_value (Array|NilClass) (defaults to: nil)

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

  • uniq (Boolean) (defaults to: false)

    If to remove duplicates from the array before sanitizing.

  • compact (Boolean) (defaults to: false)

    If to compact the array before sanitizing.

  • flatten (Boolean) (defaults to: false)

    If to flatten the array before sanitizing.

  • sanitizer (Symbol|nil) (defaults to: 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.



82
83
84
85
86
# File 'lib/lazier/object.rb', line 82

def ensure_array(default_value = nil, uniq = false, compact = false, flatten = false, sanitizer = nil, &block)
  rv = is_a?(::Array) ? dup : (default_value || [self])
  rv = manipulate_array(rv, uniq, compact, flatten).collect(&(block || sanitizer)) if block_given? || sanitizer
  manipulate_array(rv, uniq, compact, flatten)
end

#ensure_hash(access = nil, default_value = nil, sanitizer = nil) ⇒ Hash

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

Parameters:

  • access (Symbol|NilClass) (defaults to: nil)

    The requested access for the keys of the returned object. Can be :strings, :symbols or indifferent. If nil the keys are not modified.

  • default_value (Hash|String|Symbol|NilClass) (defaults to: nil)

    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) (defaults to: nil)

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

Returns:

  • (Hash)

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



94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
# File 'lib/lazier/object.rb', line 94

def ensure_hash(access = nil, default_value = nil, sanitizer = nil)
  default_value = {} if default_value.nil?

  rv = if is_a?(::Hash) then
    self
  elsif default_value.is_a?(::Hash) then
    default_value
  else
    key = default_value.is_a?(::String) || default_value.is_a?(::Symbol) ? default_value : :key
    {key => self}
  end

  if block_given? || sanitizer then
    rv = rv.inject({}) {|h, (k, v)|
      h[k] = block_given? ? yield(v) : v.send(sanitizer)
      h
    }
  end

  rv.respond_to?(:ensure_access) ? rv.ensure_access(access) :rv
end

#ensure_string(default_value = "", stringifier = :to_s) ⇒ String

Makes sure that the object is a string.

Parameters:

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

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

  • stringifier (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.



69
70
71
# File 'lib/lazier/object.rb', line 69

def ensure_string(default_value = "", stringifier = :to_s)
  !nil? ? (block_given? ? yield(self, default_value) : send(stringifier)) : default_value
end

#for_debug(format = :yaml, as_exception = true) ⇒ String

Inspects an object.

Parameters:

  • format (defaults to: :yaml)

    The format to use.

  • as_exception (Boolean) (defaults to: true)

    If raise an exception.

Returns:

  • (String)

    The object inspected and formatted.



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

def for_debug(format = :yaml, as_exception = true)
  rv = case format
    when :pretty_json
      ::JSON.pretty_generate(self)
    else
      send("to_#{format}")
  end

  as_exception ? raise(::Lazier::Exceptions::Debug.new(rv)) : rv
end

#format_boolean(true_name = nil, false_name = nil) ⇒ String

Formats a boolean.

Parameters:

  • true_name (String) (defaults to: nil)

    The string representation of true. Defaults to Yes.

  • false_name (String) (defaults to: nil)

    The string representation of false. Defaults to No.

Returns:

  • (String)

    The string representation of the object.

See Also:



173
174
175
176
# File 'lib/lazier/object.rb', line 173

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

#format_number(precision = nil, decimal_separator = nil, add_string = nil, k_separator = nil) ⇒ String

Formats a number.

Parameters:

  • precision (Fixnum) (defaults to: nil)

    The precision to show.

  • decimal_separator (String) (defaults to: nil)

    The string to use as decimal separator.

  • add_string (String) (defaults to: nil)

    The string to append to the number.

  • k_separator (String) (defaults to: nil)

    The string to use as thousands separator.

Returns:

  • (String)

    The string representation of the object.

See Also:



155
156
157
158
159
160
161
162
163
164
165
# File 'lib/lazier/object.rb', line 155

def format_number(precision = nil, decimal_separator = nil, add_string = nil, k_separator = nil)
  if is_number? then
    settings = ::Lazier.settings.format_number
    add_string ||= settings[:add_string]
    format, unit = (add_string  ? ["%n %u", add_string] : ["%n", ""])

    number_to_currency(self, {precision: [precision || settings[:precision], 0].max, separator: decimal_separator || settings[:decimal_separator], delimiter: k_separator || settings[:k_separator], format: format, unit: unit})
  else
    nil
  end
end

#indexize(length = 2, filler = "0", formatter = :rjust) ⇒ String

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

Parameters:

  • length (Fixnum) (defaults to: 2)

    The minimum length of the label.

  • filler (String) (defaults to: "0")

    The minimum length of the label.

  • formatter (Symbol) (defaults to: :rjust)

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

Returns:

  • (String)

    The object inspected and formatted.



184
185
186
# File 'lib/lazier/object.rb', line 184

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

#is_boolean?Boolean

Checks if the object is a valid boolean value.

Returns:

  • (Boolean)

    true is a valid boolean value, false otherwise.



50
51
52
# File 'lib/lazier/object.rb', line 50

def is_boolean?
  is_a?(::TrueClass) || !self || to_s =~ ::Lazier::Object::BOOLEAN_MATCHER
end

#is_float?Boolean Also known as: is_number?

Checks if the object is a valid float.

Returns:

  • (Boolean)

    true is a valid float, false otherwise.



42
43
44
# File 'lib/lazier/object.rb', line 42

def is_float?
  is_a?(::Numeric) || is_a?(::TrueClass) || !self || normalize_number =~ ::Lazier::Object::FLOAT_MATCHER
end

#is_integer?Boolean

Checks if the object is a valid integer.

Returns:

  • (Boolean)

    true is a valid integer, false otherwise.



35
36
37
# File 'lib/lazier/object.rb', line 35

def is_integer?
  is_a?(::Integer) || is_a?(::TrueClass) || !self || normalize_number =~ ::Lazier::Object::INTEGER_MATCHER
end

#normalize_numberString

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

Returns:

  • (String)

    The normalized number.



28
29
30
# File 'lib/lazier/object.rb', line 28

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

#round_to_precision(precision = 2) ⇒ Float

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.



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

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

#to_booleanBoolean

Converts the object to a boolean.

Returns:

  • (Boolean)

    The boolean representation of the object.



119
120
121
# File 'lib/lazier/object.rb', line 119

def to_boolean
  is_a?(TrueClass) || self == 1.0 || self == 1 || ensure_string =~ ::Lazier::Object::BOOLEAN_TRUE_MATCHER || false
end

#to_float(default_value = 0.0) ⇒ Float

Converts the object to a float.

Parameters:

  • default_value (Float) (defaults to: 0.0)

    The value to return if the conversion is not possible.

Returns:

  • (Float)

    The float representation of the object.



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

def to_float(default_value = 0.0)
  is_float? ? ::Kernel.Float(is_a?(::Numeric) ? self : normalize_number) : default_value
end

#to_integer(default_value = 0) ⇒ Fixnum

Converts the object to a integer.

Parameters:

  • default_value (Fixnum) (defaults to: 0)

    The value to return if the conversion is not possible.

Returns:

  • (Fixnum)

    The integer representation of the object.



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

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