Class: DBF::Database::Foxpro

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

Instance Method Summary collapse

Constructor Details

#initialize(path) ⇒ Foxpro

Opens a DBF::Database::Foxpro Examples:

# working with a database stored on the filesystem
db = DBF::Database::Foxpro.new 'path_to_db/database.dbc'

Calling a table

contacts = db.contacts.record(0)

Parameters:

  • path (String)


23
24
25
26
27
28
29
30
# File 'lib/dbf/database/foxpro.rb', line 23

def initialize(path)
  @path = path
  @dirname = File.dirname(@path)
  @db = DBF::Table.new(@path)
  @tables = extract_dbc_data
rescue Errno::ENOENT
  raise DBF::FileNotFoundError, "file not found: #{path}"
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object

:nodoc:



72
73
74
75
# File 'lib/dbf/database/foxpro.rb', line 72

def method_missing(method, *args) # :nodoc:
  name = method.to_s
  table_names.index(name) ? table(name) : super
end

Instance Method Details

#respond_to_missing?(method) ⇒ Boolean

Returns:

  • (Boolean)


77
78
79
# File 'lib/dbf/database/foxpro.rb', line 77

def respond_to_missing?(method, *)
  table_names.index(method.to_s) || super
end

#table(name) ⇒ DBF::Table

Returns table with given name

Parameters:

  • name (String)

Returns:



40
41
42
# File 'lib/dbf/database/foxpro.rb', line 40

def table(name)
  Table.new(table_path(name), long_names: @tables[name])
end

#table_namesObject



32
33
34
# File 'lib/dbf/database/foxpro.rb', line 32

def table_names
  @tables.keys
end

#table_path(name) ⇒ String

Searches the database directory for the table's dbf file and returns the absolute path. Ensures case-insensitivity on any platform.

Parameters:

  • name (String)

Returns:

  • (String)

Raises:



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/dbf/database/foxpro.rb', line 49

def table_path(name)
  name = name.to_s
  raise DBF::FileNotFoundError, "related table not found: #{name}" if name.empty? || name.include?("\x00")

  # Treat the container-supplied name as an untrusted basename so that
  # path separators and ".." cannot escape the database directory.
  # Match case-insensitively by scanning the directory rather than
  # globbing, so glob metacharacters (`{}`, `*`, `?`, `[]`) in the name
  # cannot trigger brace-expansion CPU exhaustion.
  target = "#{File.basename(name)}.dbf"
  entry = Dir.children(@dirname).find { |child| child.casecmp?(target) }
  path = entry && File.join(@dirname, entry)

  raise DBF::FileNotFoundError, "related table not found: #{name}" unless path && File.exist?(path)

  # Defense in depth: confirm the resolved file really is inside the
  # database directory before opening it.
  contained = File.realpath(path).start_with?("#{File.realpath(@dirname)}#{File::SEPARATOR}")
  raise DBF::FileNotFoundError, "related table not found: #{name}" unless contained

  path
end