Method: Puppet::Pops::Types::PFloatType.new_function

Defined in:
lib/puppet/pops/types/types.rb

.new_function(type) ⇒ Object

Returns a new function that produces a Float value



1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
# File 'lib/puppet/pops/types/types.rb', line 1234

def self.new_function(type)
  @new_function ||= Puppet::Functions.create_loaded_function(:new_float, type.loader) do
    local_types do
      type "Convertible = Variant[Numeric, Boolean, Pattern[/#{FLOAT_PATTERN}/], Timespan, Timestamp]"
      type 'NamedArgs   = Struct[{from => Convertible, Optional[abs] => Boolean}]'
    end

    dispatch :from_args do
      param          'Convertible',  :from
      optional_param 'Boolean',      :abs
    end

    dispatch :from_hash do
      param          'NamedArgs', :hash_args
    end

    argument_mismatch :on_error do
      param          'Any',     :from
      optional_param 'Boolean', :abs
    end

    def from_args(from, abs = false)
      result = from_convertible(from)
      abs ? result.abs : result
    end

    def from_hash(args_hash)
      from_args(args_hash['from'], args_hash['abs'] || false)
    end

    def from_convertible(from)
      case from
      when Float
        from
      when Integer
        Float(from)
      when Time::TimeData
        from.to_f
      when TrueClass
        1.0
      when FalseClass
        0.0
      else
        begin
          # support a binary as float
          if from[0] == '0' && from[1].casecmp('b').zero?
            from = Integer(from)
          end
          Float(from)
        rescue TypeError => e
          raise TypeConversionError, e.message
        rescue ArgumentError => e
          # Test for special case where there is whitespace between sign and number
          match = Patterns::WS_BETWEEN_SIGN_AND_NUMBER.match(from)
          if match
            begin
              # Try again, this time with whitespace removed
              return from_args(match[1] + match[2])
            rescue TypeConversionError
              # Ignored to retain original error
            end
          end
          raise TypeConversionError, e.message
        end
      end
    end

    def on_error(from, _ = false)
      if from.is_a?(String)
        _("The string '%{str}' cannot be converted to Float") % { str: from }
      else
        t = TypeCalculator.singleton.infer(from).generalize
        _("Value of type %{type} cannot be converted to Float") % { type: t }
      end
    end
  end
end