Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby get parent dir of current file

I have simple script that should read excel and print two cells:

require 'rubygems'
gem 'ruby-ole','1.2.11.4'
require 'spreadsheet'

class Filter
    # Gets zipcode range
    def get_zipcode_range
        wb = Spreadsheet.open "../data/zipcode_range.xls"
        sheet = wb.worksheet 0
        [sheet.cell(0, 0), sheet.cell(0, 1)]
    end
end

f = Filter.new
puts f.get_zipcode_range

File structure is as follows:

FilterExcel
  data
    zipcode_range.xls
  lib
    filter.rb

When I open command prompt and go to FilterExcel\lib and run:

ruby filter.rb

It gives expected output:

3911AW

3911ZZ

But when I run script from projects root folder, FilterExcel, then it raises error:

C:\Documents and Settings\Erik\FilterExcel>ruby lib\filter.rb C:/Ruby193/lib/ruby/gems/1.9.1/gems/spreadsheet-0.7.4/lib/spreadsheet.rb:68:in 'initialize': No such file or directory - ../data/zipcode_range.xls (Errno::ENOENT) from C:/Ruby193/lib/ruby/gems/1.9.1/gems/spreadsheet-0.7.4/lib/spreadsheet.rb:68:in 'open' from C:/Ruby193/lib/ruby/gems/1.9.1/gems/spreadsheet-0.7.4/lib/spreadsheet.rb:68:in 'open' from lib/filter.rb:56:in 'get_zipcode_range' from lib/filter.rb:63:in ''

P.S. I use Windows XP if that matters.

like image 537
Иван Бишевац Avatar asked Feb 12 '26 20:02

Иван Бишевац


1 Answers

You should use File.expand_path docs:

wb = Spreadsheet.open File.expand_path("../data/zipcode_range.xls", __FILE__)

Assuming, that the file you posted lies in the same directory as data/. If data/ is in the parent directory of your current Ruby file, go up twice:

wb = Spreadsheet.open File.expand_path("../../data/zipcode_range.xls", __FILE__)

The first ../ always neutralizes the __FILE__ when using File.expand_path this way. If you are not sure, make a debugging output of the file path that was generated:

puts File.expand_path("../data/zipcode_range.xls", __FILE__)
like image 99
Christoph Petschnig Avatar answered Feb 16 '26 00:02

Christoph Petschnig