Module: KBTypeConversionsMixin

Included in:
KBIndex, KBTableRec
Defined in:
lib/og/vendor/kirbybase.rb

Overview


KBTypeConversionsMixin


Constant Summary collapse

UNENCODE_RE =
/&(?:amp|linefeed|carriage_return|substitute|pipe);/

Instance Method Summary collapse

Instance Method Details

#convert_to(data_type, s) ⇒ Object


convert_to




1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
# File 'lib/og/vendor/kirbybase.rb', line 1392

def convert_to(data_type, s)
    return nil if s.empty? or s.nil?

    case data_type
    when :String
        if s =~ UNENCODE_RE
            return s.gsub('&linefeed;', "\n").gsub('&carriage_return;',
             "\r").gsub('&substitute;', "\032").gsub('&pipe;', "|"
             ).gsub('&', "&")
        else
            return s
        end
    when :Integer
        return s.to_i
    when :Float
        return s.to_f
    when :Boolean
        if ['false', 'False', nil, false].include?(s)
            return false
        else
            return true
        end
    when :Time
        return Time.parse(s)    
    when :Date
        return Date.parse(s)
    when :DateTime
        return DateTime.parse(s)
    when :YAML
        # This code is here in case the YAML field is the last
        # field in the record.  Because YAML normall defines a
        # nil value as "--- ", but KirbyBase strips trailing
        # spaces off the end of the record, so if this is the
        # last field in the record, KirbyBase will strip the
        # trailing space off and make it "---".  When KirbyBase
        # attempts to convert this value back using to_yaml,
        # you get an exception.
        if s == "---"
            return nil
        elsif s =~ UNENCODE_RE
            y = s.gsub('&linefeed;', "\n").gsub('&carriage_return;',
             "\r").gsub('&substitute;', "\032").gsub('&pipe;', "|"
             ).gsub('&', "&")
            return YAML.load(y)
        else
            return YAML.load(s)
        end
    when :Memo
        memo = KBMemo.new(@tbl.db, s)
        memo.read_from_file
        return memo
    when :Blob
        blob = KBBlob.new(@tbl.db, s)
        blob.read_from_file
        return blob
    else
        raise "Invalid field type: %s" % data_type
    end
end