Class: FightCSV::Field

Inherits:
Object
  • Object
show all
Defined in:
lib/fight_csv/field.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(matcher, options = {}) ⇒ Field

Returns a new instance of Field.



9
10
11
# File 'lib/fight_csv/field.rb', line 9

def initialize(matcher, options = {})
	@matcher = matcher
end

Instance Attribute Details

#matcherObject

Returns the value of attribute matcher.



7
8
9
# File 'lib/fight_csv/field.rb', line 7

def matcher
  @matcher
end

Instance Method Details

#identifierObject



13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/fight_csv/field.rb', line 13

def identifier
  if super
    super
  else
    case self.matcher
    when String
      self.matcher.downcase.to_sym
    else
      raise ArgumentError, "Please specify an identifier"
    end
  end
end

#ivar_symbolObject



60
61
62
# File 'lib/fight_csv/field.rb', line 60

def ivar_symbol
	:"@#{self.identifier}"
end

#match(row, header = nil) ⇒ Object



43
44
45
46
47
48
49
50
51
52
# File 'lib/fight_csv/field.rb', line 43

def match(row, header = nil)
	case self.matcher
	when Integer
		row[matcher-1]
	else
		raise ArgumentError, 'No header is provided, but a matcher other than an Integer requires one' unless header
		index = header.index  { |n| self.matcher === n }
		index ? row[index] : nil
	end
end

#process(row, header = nil) ⇒ Object



54
55
56
57
58
# File 'lib/fight_csv/field.rb', line 54

def process(row, header = nil)
	if match = self.match(row, header)
		self.converter ? self.converter.call(match) : match
	end
end

#validate(row, header = nil) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/fight_csv/field.rb', line 26

def validate(row, header = nil)
	match = self.match(row, header).to_s
	if self.validator.respond_to?(:call) 
		result = self.validator.call(match)
		verb = "pass"
	else
		result = (self.validator === match)
		verb = "match"
	end

	unless result
		{ valid: false, error: "#{self.identifier.inspect} must #{verb} #{self.validator}, but was #{match.inspect}"}
	else
		{ valid: true }
	end
end