Class: RandomJpg::Runner

Inherits:
Object
  • Object
show all
Defined in:
lib/random_jpg/runner.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args = []) ⇒ Runner

Returns a new instance of Runner.



7
8
9
10
11
12
13
# File 'lib/random_jpg/runner.rb', line 7

def initialize(args = [])
  @path   = "/tmp/random.jpg"
  @daemon = false
  @force  = false
  @loader = Loader::Flickr.new
  parse_options(args)
end

Instance Attribute Details

#daemonObject (readonly)

Returns the value of attribute daemon.



5
6
7
# File 'lib/random_jpg/runner.rb', line 5

def daemon
  @daemon
end

#forceObject (readonly)

Returns the value of attribute force.



5
6
7
# File 'lib/random_jpg/runner.rb', line 5

def force
  @force
end

#loaderObject (readonly)

Returns the value of attribute loader.



5
6
7
# File 'lib/random_jpg/runner.rb', line 5

def loader
  @loader
end

#pathObject (readonly)

Returns the value of attribute path.



5
6
7
# File 'lib/random_jpg/runner.rb', line 5

def path
  @path
end

Instance Method Details

#create_pipe(path, force = false) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/random_jpg/runner.rb', line 46

def create_pipe(path, force = false)
  if File.exists?(path)
    if force
      raise Error.new("Permission denied: #{path}") unless File.writable?(path)
      File.unlink(path)
    else
      raise Error.new("Unable to create pipe: #{path}, file exists. Use --force to overwrite.")
    end
  end

  system "mkfifo #{path}"
end

#parse_options(args) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/random_jpg/runner.rb', line 15

def parse_options(args)
  OptionParser.new do |opts|
    opts.banner = "Usage: random_jpg [options]"
    opts.separator ""
    opts.separator "Options:"
    opts.on("-p", "--path PATH", "Full path to the random image file") do |path|
      @path = path
    end
    opts.on("-d", "--daemon", "Run in the background") do
      @daemon = true
    end
    opts.on("-f", "--force", "Force overwrite if a file exists at given path") do
      @force = true
    end
    opts.on("-l LOADER", [:flickr, :imgur], "Image source (flickr [default], imgur)") do |loader|
      @loader = Loader::Imgur.new if loader == :imgur
    end
    opts.on_tail("-h", "--help", "Show this message") do
      puts opts
      exit
    end
  end.parse!(args)
end

#runObject



39
40
41
42
43
44
# File 'lib/random_jpg/runner.rb', line 39

def run
  create_pipe(path, force)
  Process.daemon if daemon
  trap("SIGINT") { File.unlink(path); exit }
  loop { loader.feed(path) }
end