Snippets

SeanB Example Dataflex DataFile export from Ruby

Created by SeanB

require 'fileutils'

class LoadFile 
  
  def filename
    "C:/Dropbox/develop/Dataflex/Test/Data/ascdpitem.dat"
  end

  def blocksize 
    512
  end 

  def blockStart 
    (512*7)
  end 

  def bcd_to_dec(bcd)
    n = 0
    nibbles = []

    bcd.bytes do |i|
      nibbles << ((i & 0xf0) >> 4 ) << (i & 0x0f)
    end       


    isNegative = (nibbles[0] == 0)
    nibbles[0] = nibbles[0] - 1 if !isNegative

    nibbles.each do |i|
      n = n * 10
      n = n + i
    end
    n = -n if isNegative 
    n
  end

  def bin_to_hex(s)
    s.each_byte.map { |b| b.to_s(16) + sTab }.join
  end


  def remove_nonascii(val,replacement)
    n=val.split("")
    val.slice!(0..val.size)
    n.each { |b|
     if b.ord< 33 || b.ord>127 then
       val.concat(replacement)
     else
       val.concat(b)
     end
    }
    val.to_s
  end

  def ReadBlock(outfile)
    puts "Reading #{filename}"
    size = File.size(filename)
    size = (size - blockStart) / blocksize 

    sTab = ","

    for k in 0..(size-1) do 
      f = IO.binread(filename,blocksize,(k*blocksize)+blockStart)

      # 4,4,20,4,4,4,1,1,6,4
      #puts bin_to_hex(f.byteslice(0,512))
      
      floc = f.byteslice(4,1).ord 

      batch = bcd_to_dec(f.byteslice(0,4)).to_s
      location = f.byteslice(4,4).to_s
      code = f.byteslice(8,20)
      bin = f.byteslice(28,4)
      orig_qty = bcd_to_dec(f.byteslice(32,4)).to_s
      actual_qty = bcd_to_dec(f.byteslice(36,4)).to_s
      updated = f.byteslice(40,1)
      qty_entered = f.byteslice(41,1)
      
      cost = (bcd_to_dec(f.byteslice(42,6))).to_f 
      cost = cost / 10000 
      cost = cost.to_s 

      qty_adjusted = bcd_to_dec(f.byteslice(48,4)).to_s

      code = ('"'+code+'"') if !code.index(",").nil?
      bin = ('"'+bin+'"') if !bin.index(",").nil?
      location = ('"'+location+'"') if !location.index(",").nil?

      #puts f
      if (location) && (floc!=0) & (location != "    ") 
        sOut = k.to_s + sTab + batch + sTab + location + sTab + code + sTab 
        sOut = sOut + bin + sTab +  orig_qty + sTab + actual_qty + sTab
        sOut = sOut + updated + sTab + qty_entered + sTab
        sOut = sOut + cost + sTab + qty_adjusted
        
        puts sOut if !sOut.index('"').nil?
        outfile.puts (sOut)

      end 
    end
  end

  def WriteReadBlock
    open(filename+".csv", 'w') { |f|
      ReadBlock(f)
    }
  end 

end 

  a = LoadFile.new()
  a.WriteReadBlock()

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.