Class: DBF::Record

Inherits:
Object
  • Object
show all
Defined in:
lib/dbf/record.rb

Overview

An instance of DBF::Record represents a row in the DBF file

Instance Method Summary collapse

Constructor Details

#initialize(data, context, offset = 0) ⇒ Record

Initialize a new DBF::Record

Parameters:

  • data (String, StringIO)

    data

  • context (DBF::RecordContext)
  • offset (Integer) (defaults to: 0)


11
12
13
14
15
16
# File 'lib/dbf/record.rb', line 11

def initialize(data, context, offset = 0)
  @data = data
  @context = context
  @offset = offset
  @to_a = nil
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object (private)

:nodoc:



113
114
115
116
117
118
119
120
121
122
123
124
# File 'lib/dbf/record.rb', line 113

def method_missing(method, *args) # :nodoc:
  key = method.to_s
  if (index = underscored_column_names.index(key))
    if @context.column_offsets && !@to_a
      column_value(index)
    else
      attributes[@context.columns[index].name]
    end
  else
    super
  end
end

Instance Method Details

#==(other) ⇒ Boolean

Equality

Parameters:

Returns:

  • (Boolean)


22
23
24
25
26
# File 'lib/dbf/record.rb', line 22

def ==(other)
  attributes == other.attributes
rescue NoMethodError
  false
end

#[](name) ⇒ Object

Reads attributes by column name

Parameters:

  • name (String, Symbol)

    key



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/dbf/record.rb', line 31

def [](name)
  key = name.to_s
  if @context.column_offsets && !@to_a
    index = column_name_index(key)
    index ? column_value(index) : nil
  elsif attributes.key?(key)
    attributes[key]
  elsif (index = underscored_column_names.index(key))
    attributes[@context.columns[index].name]
  end
end

#attributesHash

Record attributes

Returns:

  • (Hash)


46
47
48
# File 'lib/dbf/record.rb', line 46

def attributes
  @attributes ||= column_names.zip(to_a).to_h
end

#match?(options) ⇒ Boolean

Do all search parameters match?

Parameters:

  • options (Hash)

Returns:

  • (Boolean)


54
55
56
# File 'lib/dbf/record.rb', line 54

def match?(options)
  options.all? { |key, value| self[key] == value }
end

#to_aArray

Maps a row to an array of values

Returns:

  • (Array)


61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/dbf/record.rb', line 61

def to_a
  @to_a ||= begin
    data = @data
    offset = @offset
    columns = @context.columns
    col_count = columns.length
    result = Array.new(col_count)
    index = 0
    while index < col_count
      column = columns[index]
      len = column.length
      raw = data.byteslice(offset, len)
      offset += len
      result[index] = decode_column(raw, column)
      index += 1
    end
    @offset = offset
    result
  end
end