Class: RunLoop::PlistBuddy

Inherits:
Object
  • Object
show all
Defined in:
lib/run_loop/plist_buddy.rb

Overview

A class for reading and writing property list values.

Why not use CFPropertyList? Because it is super wonky. Among its other faults, it matches Boolean to a string type with ‘true/false’ values which is problematic for our purposes.

Instance Method Summary collapse

Instance Method Details

#create_plist(path) ⇒ Object

Creates an new empty plist at ‘path`.

Is not responsible for creating directories or ensuring write permissions.



76
77
78
79
80
81
82
83
84
85
86
# File 'lib/run_loop/plist_buddy.rb', line 76

def create_plist(path)
  File.open(path, 'w') do |file|
    file.puts "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
    file.puts "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">"
    file.puts "<plist version=\"1.0\">"
    file.puts '<dict>'
    file.puts '</dict>'
    file.puts '</plist>'
  end
  path
end

#plist_key_exists?(key, file, opts = {}) ⇒ Boolean

Checks if the key exists in plist.

Options Hash (opts):

  • :verbose (Boolean) — default: false

    controls log level



35
36
37
# File 'lib/run_loop/plist_buddy.rb', line 35

def plist_key_exists?(key, file, opts={})
  plist_read(key, file, opts) != nil
end

#plist_read(key, file, opts = {}) ⇒ String

Reads key from file and returns the result.

Options Hash (opts):

  • :verbose (Boolean) — default: false

    controls log level

Raises:

  • (ArgumentError)

    if nil or empty key



16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/run_loop/plist_buddy.rb', line 16

def plist_read(key, file, opts={})
  if key.nil? or key.length == 0
    raise(ArgumentError, "key '#{key}' must not be nil or empty")
  end
  cmd = build_plist_cmd(:print, {:key => key}, file)
  res = execute_plist_cmd(cmd, opts)
  if res == "Print: Entry, \":#{key}\", Does Not Exist"
    nil
  else
    res
  end
end

#plist_set(key, type, value, file, opts = {}) ⇒ Boolean

Replaces or creates the value of key in the file.

Options Hash (opts):

  • :verbose (Boolean) — default: false

    controls log level

Raises:

  • (ArgumentError)

    if nil or empty key



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/run_loop/plist_buddy.rb', line 49

def plist_set(key, type, value, file, opts={})
  default_opts = {:verbose => false}
  merged = default_opts.merge(opts)

  if key.nil? or key.length == 0
    raise(ArgumentError, "key '#{key}' must not be nil or empty")
  end

  cmd_args = {:key => key,
              :type => type,
              :value => value}

  if plist_key_exists?(key, file, merged)
    cmd = build_plist_cmd(:set, cmd_args, file)
  else
    cmd = build_plist_cmd(:add, cmd_args, file)
  end

  res = execute_plist_cmd(cmd, merged)
  res == ''
end