This repository has been archived by the owner on Oct 18, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
user.rb
75 lines (66 loc) · 1.94 KB
/
user.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
66
67
68
69
70
71
72
73
74
75
require 'forwardable'
module NginxStage
# A String-like Class that includes helper methods to better describe the
# user on the local system.
class User
extend Forwardable
# @!method name
# The user name
# @return [String] the user name
# @!method uid
# The user's id
# @return [Integer] the user id
# @!method gid
# The user's group id
# @return [Integer] the group id
# @!method gecos
# The user's real name
# @return [String] the real name
# @!method dir
# The user's home directory
# @return [String] the home path
# @!method shell
# The user's shell
# @return [String] the shell
delegate [:name, :uid, :gid, :gecos, :dir, :shell] => :@passwd
# List of all groups that user belongs to
# @return [Array<String>] list of groups user is in
attr_reader :groups
# @param user [String] the user name defining this object
# @raise [InvalidUser] if user doesn't exist on local system
def initialize(user)
@passwd = Etc.getpwnam user.to_s
@group = Etc.getgrgid gid
@groups = get_groups
rescue ArgumentError
raise InvalidUser, "user doesn't exist: #{user}"
end
# User's primary group name
# @return [String] the primary group name
def group
@group.name
end
# Members of user's primary group
# @return [Array<String>] list of users in primary group
def group_mem
@group.mem
end
# Convert object to string using user name as string value
# @return [String] the user name
def to_s
@passwd.name
end
# This object is string-like and returns the user name when treated as a
# string
# @return [String] the user name
def to_str
@passwd.name
end
private
# Use `id` to get list of groups as the /etc/group file can give
# erroneous results
def get_groups
`id -nG #{name}`.split(' ')
end
end
end