forked from fjordllc/ruby-practices
/
ls_file.rb
65 lines (50 loc) · 1.04 KB
/
ls_file.rb
1
2
3
4
5
6
7
8
9
10
11
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# frozen_string_literal: true
require 'etc'
require 'pathname'
class LsFile
def self.all(params)
pattern = File.join(params.target_directory, '*')
flag = params.dot_match? ? File::FNM_DOTMATCH : 0
paths = Dir.glob(pattern, flag)
paths << File.join(params.target_directory, '..') if params.dot_match?
sorted_paths = params.reverse? ? paths.sort.reverse : paths.sort
sorted_paths.map { |path| LsFile.new(path) }
end
def initialize(path)
@pathname = Pathname.new(path)
end
def name
@pathname.basename.to_s
end
def block_size
file_stat.blocks
end
def file_type
file_stat.ftype
end
def permission
file_stat.mode.to_s(8)[-3..]
end
def link_count
@pathname.directory? ? @pathname.entries.size : 1
end
def owner_name
Etc.getpwuid(file_stat.uid).name
end
def group_name
Etc.getgrgid(file_stat.gid).name
end
def bytesize
@pathname.size
end
def mtime
@pathname.mtime
end
def to_s
name
end
private
def file_stat
@pathname.stat
end
end