Module: CsvRecord

Defined in:
lib/csvrecord/builder.rb,
lib/csvrecord/base.rb,
lib/csvrecord/version.rb

Overview

(record) builder mini language / domain-specific language (dsl)

Defined Under Namespace

Classes: Base, Builder, Field, Type

Constant Summary collapse

MAJOR =

todo: namespace inside version or something - why? why not??

0
MINOR =
4
PATCH =
0
VERSION =
[MAJOR,MINOR,PATCH].join('.')

Class Method Summary collapse

Class Method Details



16
17
18
# File 'lib/csvrecord/version.rb', line 16

def self.banner
  "csvrecord/#{VERSION} on Ruby #{RUBY_VERSION} (#{RUBY_RELEASE_DATE}) [#{RUBY_PLATFORM}]"
end

.build_class(headers) ⇒ Object

“magic” lazy auto-build schema from headers versions



106
107
108
109
110
111
112
113
114
115
116
117
118
119
# File 'lib/csvrecord/base.rb', line 106

def self.build_class( headers )   ## check: find a better name - why? why not?

  ## (auto-)build record class from an array of headers

  ##   add fields (all types will be string for now)

  clazz = Class.new(Base)
  headers.each do |header|
    ## downcase and remove all non-ascii chars etc.

    ##  todo/fix: remove all non-ascii chars!!!

    ##  todo: check if header starts with a number too!!

    name = header.downcase.gsub( ' ', '_' )
    name = name.to_sym   ## symbol-ify

    clazz.field( name )
  end
  clazz
end

.define(&block) ⇒ Object



81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
# File 'lib/csvrecord/base.rb', line 81

def self.define( &block )
  builder = Builder.new
  if block.arity == 1
    block.call( builder )
    ## e.g. allows "yield" dsl style e.g.

    ##  CsvRecord.define do |rec|

    ##     rec.string :team1

    ##     rec.string :team2

    ##  end

    ##

  else
    builder.instance_eval( &block )
    ## e.g. shorter "instance eval" dsl style e.g.

    ##  CsvRecord.define do

    ##     string :team1

    ##     string :team2

    ##  end

  end
  builder.to_record
end

.foreach(path, sep: Csv.config.sep, &block) ⇒ Object



128
129
130
131
132
133
# File 'lib/csvrecord/base.rb', line 128

def self.foreach( path, sep: Csv.config.sep, &block )
  headers = CsvReader.header( path, sep: sep )

  clazz = build_class( headers )
  clazz.foreach( path, sep: sep, &block )
end

.read(path, sep: Csv.config.sep) ⇒ Object



121
122
123
124
125
126
# File 'lib/csvrecord/base.rb', line 121

def self.read( path, sep: Csv.config.sep )
  headers = CsvReader.header( path, sep: sep )

  clazz = build_class( headers )
  clazz.read( path, sep: sep )
end

.rootObject



20
21
22
# File 'lib/csvrecord/version.rb', line 20

def self.root
  File.expand_path( File.dirname(File.dirname(File.dirname(__FILE__))) )
end

.versionObject



12
13
14
# File 'lib/csvrecord/version.rb', line 12

def self.version
  VERSION
end