module DataBase
def self.init
@classlist = []
end
def self.classlist
return @classlist
end
def self.classlist= obj
@classlist = obj
end
module DataBase::CSV
attr_reader :data_table
def self.load_data(filename)
data = readtable(filename)
class_name = make_data_class(data, filename)
@data_table = fill_datas(data, class_name)
end
#生成数据文件对应的类
def self.make_data_class(data, filename)
names = data[0]
data_class = DataBase.const_set(filename.capitalize, Class.new)
data_class.class_eval do
names.each{|i| attr_accessor i}
define_method(:initialize) do |val|
names.each_with_index do |name, i|
instance_variable_set("@"+name, eval(val[i]))
end
end
end
DataBase.classlist.push(filename)
return data_class
end
#填充数据
def self.fill_datas(data, class_name)
table = []
table[0] = nil
#删除头数据
data.delete_at(0)
data.each_index{|i| table.push(class_name.new(data[i]))}
return table
end
#读取
def self.readtable(filename)
data = File.open("#{$DATAPATH}/#{filename}.csv", "r") do |f|
f = f.readlines()
f = f.each_index do |i|
f[i] = f[i].split(",")
f[i][-1] = f[i][-1].chomp
end
end
end
end
end