require 'fastercsv' class Array # transforms the collection into a csv formatted string # # each column is described by a label/property pair # eg [["Published","created_at"]] generates a column with label "Published" and the data value being the created_at field # def to_csv(columns) FasterCSV.generate do |csv| csv << columns.collect{|c| c.to_a.first } self.each do |result| csv << columns.collect{|c| c.to_a.last }.collect{|c| result.send(c) } end end end def select_with_index(&block) selected = [] self.each_index do |i| selected << self[i] if block.call(self[i],i) == true end selected end # # to_auto_complete_list(:label => ["? (?)",:auditable_type,:auditable_id], :value => ["?-?",:auditable_type,:auditable_id]) # def to_auto_complete_list(opts = {}) if opts.blank? || opts[:label].blank? || opts[:value].blank? || (opts[:label].kind_of?(Array) && opts[:label].size < 2) return [] end list = collect do |obj| [active_record_type_condition_rendering(opts[:label],obj), active_record_type_condition_rendering(opts[:value],obj)] end # a :include_blank key # if it == true then just include a blank array (ie all elements) # if it == Array then render it using the AR rendering eg ["?",property] if opts[:include_blank] == true list.unshift(["All",""]) elsif opts[:include_blank] list = collect {|obj| [active_record_type_condition_rendering(opts[:include_blank],obj), active_record_type_condition_rendering(opts[:include_blank],obj)] }.uniq + list end list.compact.uniq end private def active_record_type_condition_rendering(format, obj) if format.kind_of?(Array) label = format.clone label_format = label.shift label_split = label_format.split('?') label_values = label.collect{|p| obj.respond_to?(p) ? obj.send(p) : "" } label_split.zip(label_values).join else obj.respond_to?(format) ? obj.send(format) : "" end end end