Class: Grizzled::Unix::User

Inherits:
Object
  • Object
show all
Defined in:
lib/grizzled/unix.rb

Overview

A User object allows you to do things with Unix users, such as (for instance) run code as that user.

Instance Method Summary collapse

Constructor Details

#initialize(id) ⇒ User

Initialize a new user. The id parameter is either a user name (string) or a UID (integer).



51
52
53
54
# File 'lib/grizzled/unix.rb', line 51

def initialize(id)
  # Find the user in the password database.
  @pwent = (id.is_a? Integer) ? Etc.getpwuid(id) : Etc.getpwnam(id)
end

Instance Method Details

#run_as(&block) ⇒ Object

Run a block of code as this user.

Parameters:

block

the block to execute as that user. It will receive this User object as a parameter.

This function will only run as ‘root’.

Example

require 'grizzled/unix'
require 'fileutils'

Grizzled::Unix::User.new('root').run_as |u|
  rm_r(File.join('/tmp', '*')) # Yeah, this is dangerous
end


73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/grizzled/unix.rb', line 73

def run_as(&block)

  # Fork the child process. Process.fork will run a given block of
  # code in the child process.
  child = Process.fork do
    # We're in the child. Set the process's user ID.
    Process.uid = @pwent.uid

    # Invoke the caller's block of code.
    block.call(self)
  end

  Process.waitpid(child)
end