File: looser_typecasting.rb

package info (click to toggle)
ruby-sequel 5.63.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 10,408 kB
  • sloc: ruby: 113,747; makefile: 3
file content (57 lines) | stat: -rw-r--r-- 1,402 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# frozen-string-literal: true
#
# The LooserTypecasting extension loosens the default database typecasting
# for the following types:
#
# :float :: use to_f instead of Float()
# :integer :: use to_i instead of Integer()
# :decimal :: use 0.0 for unsupported strings
# :string :: silently allow hash and array conversion to string
#
# This also removes bytesize checks for string inputs for float, integer
# and decimal conversions.
#
# To load the extension into the database:
#
#   DB.extension :looser_typecasting
#
# Related module: Sequel::LooserTypecasting

#
module Sequel
  module LooserTypecasting
    private

    # Typecast the value to a Float using to_f instead of Kernel.Float
    def typecast_value_float(value)
      value.to_f
    end

    # Typecast the value to an Integer using to_i instead of Kernel.Integer
    def typecast_value_integer(value)
      value.to_i
    end

    # Typecast the value to an String using to_s instead of Kernel.String
    def typecast_value_string(value)
      value.to_s
    end

    if RUBY_VERSION >= '2.4'
      def _typecast_value_string_to_decimal(value)
        BigDecimal(value)
      rescue
        BigDecimal('0.0')
      end
    else
      # :nocov:
      def _typecast_value_string_to_decimal(value)
        BigDecimal(value)
      end
      # :nocov:
    end
  end

  Database.register_extension(:looser_typecasting, LooserTypecasting)
end