Class: Djinn::Base::Dsl::ConfigHelper

Inherits:
Object
  • Object
show all
Defined in:
lib/djinn/base/dsl.rb

Overview

Used internally to read configuration blocks

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(&block) ⇒ ConfigHelper

Returns a new instance of ConfigHelper.



43
44
45
46
# File 'lib/djinn/base/dsl.rb', line 43

def initialize &block
  @config_items = []
  instance_eval(&block) if block_given?
end

Instance Attribute Details

#configObject

Returns the value of attribute config.



41
42
43
# File 'lib/djinn/base/dsl.rb', line 41

def config
  @config
end

#config_itemsObject

Returns the value of attribute config_items.



41
42
43
# File 'lib/djinn/base/dsl.rb', line 41

def config_items
  @config_items
end

Instance Method Details

#add(key, &block) ⇒ Object

Add a posix-style switch to your Djinn



49
50
51
# File 'lib/djinn/base/dsl.rb', line 49

def add key, &block
  @config_items << ConfigItem.new(:posix, key, &block)
end

#add_flag(key, &block) ⇒ Object

Add a simple flag switch to your daemon



54
55
56
# File 'lib/djinn/base/dsl.rb', line 54

def add_flag key, &block
  @config_items << ConfigItem.new(:flag, key, &block)
end

#parse_config!(config, &block) ⇒ Object

Parses the configuration items created by executing the configuration block



60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/djinn/base/dsl.rb', line 60

def parse_config!(config, &block)
  options = OptionParser.new do |opts|
    opts.banner = "Usage: djinn_file [OPTIONS]"
    opts.on("-N", "--no-daemon", "Don't run in the background") do
      config[:__daemonize] = false
    end
    opts.on("--stop", "Stop the Djinn, if possible") do
      config[:__stop] = true
    end
    opts.on_tail("-h", "--help", "Prints this message") do
      puts opts
      exit(0)
    end
    @config_items.each { |c| c.parse!(opts, config) }
  end
  yield options if block_given?
  options.parse!
  #Apply defaults
  @config_items.each do |ci|
    config[ci.key] = ci.default_value if ci.has_default? unless config.include?(ci.key)
  end
  # Check for missing arguments
  @config_items.each do |ci|
    if ci.required?
      puts "Missing argument: #{ci.key}\n\n#{options}"
      exit(1)
    end unless config.include?(ci.key) or config.include?(:__stop)
  end
rescue OptionParser::InvalidOption => e
  puts e.message
  exit(1)
end