class FileBrowserModel

Functions related to retrieving and formatting information related to directories and their contents.

Attributes

current_path[RW]
files[RW]
page[RW]
selected[RW]

Public Class Methods

new(starting_path, options = {}) click to toggle source
# File lib/terminal-file-picker/file_browser_model.rb, line 6
def initialize(starting_path, options = {})
  @options = options
  @current_path = starting_path
  @page = 0
  @selected = 0
  @files = order_files(files_in_dir)
end

Public Instance Methods

files_in_dir() click to toggle source
# File lib/terminal-file-picker/file_browser_model.rb, line 14
def files_in_dir
  date_format = @options.fetch(:date_format, '%d/%m/%Y')
  time_format = @options.fetch(:time_format, '%H:%M')

  Dir.entries(@current_path).map do |f|
    file_path = File.join(@current_path, f)

    name = add_indicator(f)

    size_bytes = File.size(file_path)

    mtime = File.mtime(file_path)
    date_mod = mtime.strftime(date_format)
    time_mod = mtime.strftime(time_format)

    [name, size_bytes, date_mod, time_mod]
  end
end
order_files(files) click to toggle source

Order files such that '.' and '..' come before all the other files.

# File lib/terminal-file-picker/file_browser_model.rb, line 35
def order_files(files)
  # Put "." and ".." at the start
  groups = files.group_by do |f|
    if f.first == './' || f.first == '../'
      :dots
    else
      :files
    end
  end

  # Sort so that "." comes before ".."
  (groups[:dots] || []).sort.reverse + (groups[:files] || [])
end
path_rel_to_start(file_name) click to toggle source
# File lib/terminal-file-picker/file_browser_model.rb, line 57
def path_rel_to_start(file_name)
  File.join(@current_path, file_name)
end
selected_absolute_path() click to toggle source

Absolute path of the currently selected file

# File lib/terminal-file-picker/file_browser_model.rb, line 50
def selected_absolute_path
  selected_file_name = @files[@selected].first
  # This may not be the absolute path (e.g. file_name may be '.')
  selected_full_path = File.join(@current_path, selected_file_name)
  File.absolute_path(selected_full_path)
end

Private Instance Methods

add_indicator(file_name) click to toggle source
# File lib/terminal-file-picker/file_browser_model.rb, line 63
def add_indicator(file_name)
  return "#{file_name}/" if File.directory?(path_rel_to_start(file_name))

  file_name
end