Module: Millionaire::Csv::ClassMethods
- Defined in:
- lib/millionaire/csv.rb
Instance Method Summary collapse
- #all ⇒ Object
- #column(name, option = {}) ⇒ Object
- #column_names ⇒ Object
- #find(line_no) ⇒ Object
- #first ⇒ Object
- #index(*name) ⇒ Object
- #indexing ⇒ Object
- #last ⇒ Object
- #load(io) ⇒ Object
- #where(query) ⇒ Object
Instance Method Details
#all ⇒ Object
85 |
# File 'lib/millionaire/csv.rb', line 85 def all; self.csv_data; end |
#column(name, option = {}) ⇒ Object
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
# File 'lib/millionaire/csv.rb', line 32 def column(name, option={}) attr_accessor name column = Millionaire::Column.new(name, option) self.columns << column option.each do |k,v| case k when :null; validates name, presence: v unless v when :length; validates name, length: {maximum: v} when :value; validates name, inclusion: {in: v} when :constraint; validates name, v when :index; index(name) when :uniq validates name, csv_uniqness: v index(name) end end end |
#column_names ⇒ Object
49 |
# File 'lib/millionaire/csv.rb', line 49 def column_names; self.columns.map(&:name); end |
#find(line_no) ⇒ Object
82 83 84 |
# File 'lib/millionaire/csv.rb', line 82 def find(line_no) csv_data[line_no.pred] end |
#first ⇒ Object
86 |
# File 'lib/millionaire/csv.rb', line 86 def first; self.csv_data.first; end |
#index(*name) ⇒ Object
51 52 53 54 55 |
# File 'lib/millionaire/csv.rb', line 51 def index(*name) name.each do |n| self.indexes[Array.wrap n] = [] end end |
#indexing ⇒ Object
57 58 59 60 61 62 63 64 |
# File 'lib/millionaire/csv.rb', line 57 def indexing self.indexes.keys.each do |k| index_data= self.csv_data.group_by do |v| k.map{|a| v.send(a) } end self.indexes[k] = index_data end end |
#last ⇒ Object
87 |
# File 'lib/millionaire/csv.rb', line 87 def last; self.csv_data.last; end |
#load(io) ⇒ Object
23 24 25 26 27 28 29 30 |
# File 'lib/millionaire/csv.rb', line 23 def load(io) self.csv_data = [] csv = ::CSV.new(io, headers: :first_row, return_headers: false) csv.each_with_index do |row,ix| self.csv_data << self.new(row.to_hash.slice(*self.column_names).merge(line_no: ix.succ)) end indexing end |
#where(query) ⇒ Object
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/millionaire/csv.rb', line 66 def where(query) if self.indexes.key? query.keys self.indexes[query.keys][query.values] else group = self.csv_data.group_by do |r| query.map{|k,v| r.send(k)} end if query.values.all? {|val| val.is_a? Array } query.values.map {|val| val.map {|v| group[Array.wrap(v)] } }.flatten else group[query.values] end end end |