Module: CsvMadness::SheetMethods::ClassMethods

Included in:
CsvMadness::Sheet
Defined in:
lib/csv_madness/sheet_methods/class_methods.rb

Instance Method Summary collapse

Instance Method Details

#add_search_path(path) ⇒ Object

Paths to be searched when CsvMadness.load( "filename.csv" ) is called.



21
22
23
24
25
26
27
28
29
# File 'lib/csv_madness/sheet_methods/class_methods.rb', line 21

def add_search_path( path )
  @search_paths ||= []
  path = Pathname.new( path ).expand_path
  unless path.directory?
    raise "The given path does not exist"
  end

  @search_paths << path unless @search_paths.include?( path )
end

#find_spreadsheet_in_filesystem(name) ⇒ Object

Search absolute/relative-to-current-dir before checking search paths.



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/csv_madness/sheet_methods/class_methods.rb', line 45

def find_spreadsheet_in_filesystem( name )
  @search_paths ||= []

  expanded_path = Pathname.new( name ).expand_path
  if expanded_path.exist?
    return expanded_path
  else   # look for it in the search paths
    @search_paths.each do |p|
      file = p.join( name )
      if file.exist? && file.file?
        return p.join( name )
      end
    end
  end

  nil
end

#from(csv_file, opts = {}) ⇒ Object



35
36
37
38
39
40
41
# File 'lib/csv_madness/sheet_methods/class_methods.rb', line 35

def from( csv_file, opts = {} )
  if f = find_spreadsheet_in_filesystem( csv_file )
    Sheet.new( f, opts )
  else
    raise "File not found."
  end
end

#getter_name(name) ⇒ Object

Used to make getter/setter names out of the original header strings. " hello;: world! " => :hello_world



6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/csv_madness/sheet_methods/class_methods.rb', line 6

def getter_name( name )
  # replace any run of non-word characters with a single "_"
  name = name.downcase.gsub( /(\W|_|\s)+/, "_" )

  # snip trailing and leading "_"
  name = name.gsub( /(^_+|_+$)/, "" )

  # add leading "_" when we'd otherwise have a method name starting with a digit
  name = "_#{name}" if name.match( /^\d/ )

  name.to_sym
end

#search_pathsObject



31
32
33
# File 'lib/csv_madness/sheet_methods/class_methods.rb', line 31

def search_paths
  @search_paths
end

#to_csv(spreadsheet, opts = {}) ⇒ Object

opts are passed to underlying CSV (:row_sep, :encoding, :force_quotes)



64
65
66
67
68
69
# File 'lib/csv_madness/sheet_methods/class_methods.rb', line 64

def to_csv( spreadsheet, opts = {} )
  out = spreadsheet.columns.to_csv
  spreadsheet.records.inject( out ) do |output, record|
    output << record.to_csv
  end
end

#write_to_file(spreadsheet, file) ⇒ Object



71
72
73
74
# File 'lib/csv_madness/sheet_methods/class_methods.rb', line 71

def write_to_file( spreadsheet, file )
  file = file.fwf_filepath.expand_path
  file.write( spreadsheet.to_csv )
end