Class: CourseraDownloader::FileStore

Inherits:
Object
  • Object
show all
Defined in:
lib/coursera_downloader/file_store.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(containing_dir) ⇒ FileStore

Returns a new instance of FileStore.



8
9
10
# File 'lib/coursera_downloader/file_store.rb', line 8

def initialize(containing_dir)
  @containing_dir = containing_dir
end

Instance Attribute Details

#containing_dirObject (readonly)

Returns the value of attribute containing_dir.



6
7
8
# File 'lib/coursera_downloader/file_store.rb', line 6

def containing_dir
  @containing_dir
end

Instance Method Details

#path(url, path_in_source = false) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/coursera_downloader/file_store.rb', line 12

def path(url, path_in_source = false)
  path = url.path
  dir_name = File.dirname(path)
  extension = File.extname(path)
  base_name = File.basename(path, extension)

  extension = ".html" unless extension.length > 0

  if url.query
    query = "?#{url.query}"
    query = CGI.escape(query)
  else
    query = ""
  end

  store_dir = File.join(@containing_dir, url.host, dir_name)
  store_dir = Util.escape_path(store_dir) if path_in_source

  file_name = "#{base_name}#{query}#{extension}"
  file_name = Util.escape_path(file_name) if path_in_source

  file_path = File.join(store_dir, file_name)

  [store_dir, file_path]
end

#relative_resource_path(containing_url, resource_url, path_in_source = true) ⇒ Object



38
39
40
41
42
43
# File 'lib/coursera_downloader/file_store.rb', line 38

def relative_resource_path(containing_url, resource_url, path_in_source = true)
  _, containing_path = path(containing_url, path_in_source)
  _, resource_path = path(resource_url, path_in_source)

  Util.path_relative_to_path(containing_path, resource_path)
end

#write(document) ⇒ Object



45
46
47
48
49
50
51
52
53
# File 'lib/coursera_downloader/file_store.rb', line 45

def write(document)
  store_dir, file_path = path(document.url)

  FileUtils.mkdir_p(store_dir)

  File.open(file_path, "wb") do |file|
    file.write(document.body)
  end
end