Class: Lame::Initializer

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

Overview

Build configurations from yaml files

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(root) ⇒ Initializer

CONTROLLER = “Controller”



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/initializer.rb', line 14

def initialize(root)
  @root = root
  @options = {
    :env => (ENV['RACK_ENV'] || :development).to_sym,
    :config => @root + '/conf/',
    :log_path => @root + '/logs',
    :verbose => false
  }
  self.set_options
  self.read_config if File.exists?(@root + '/conf/config.yml')
  self.read_database_config if File.exists?(@root + '/conf/database.yml')
  self.set_log
  # Load all common ruby files in lib, and ext directories
  Dir[ @root + "/lib/*.rb"].each {|f| require f}
  # Load modules and classes for controller
  self.instantiate_controller(@root + '/ext/controller', '.rb')
  # Load models
  Dir[ @root + "/ext/record/*.rb"].each {|f| require f}
  # Load views
end

Instance Attribute Details

#databaseObject (readonly)

Returns the value of attribute database.



10
11
12
# File 'lib/initializer.rb', line 10

def database
  @database
end

#systemObject (readonly)

Returns the value of attribute system.



10
11
12
# File 'lib/initializer.rb', line 10

def system
  @system
end

Instance Method Details

#build_modules(sub_dir_hash) ⇒ Object



121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
# File 'lib/initializer.rb', line 121

def build_modules(sub_dir_hash)
  nmodule = Module.new
  sub_dir_hash.each_pair do |k,v|
    if Object.constants.include?(k)
      # This is the top module
      nmodule = nmodule.const_get(v)
      next
    elsif nmodule.constants.include?(k)
      # This module already exists
      nmodule = nmodule.const_get(v)
    else
      # This is a new module
      nmodule = nmodule.const_set(v, Module.new)
    end
  end
  return nmodule
end

#camel_name(string) ⇒ Object



160
161
162
163
# File 'lib/initializer.rb', line 160

def camel_name(string)
  name = string.split("_").map {|s| s.capitalize }.join
  return name
end

#camel_path(path, ext) ⇒ Object



165
166
167
168
169
# File 'lib/initializer.rb', line 165

def camel_path(path, ext)
  new_path = File.join(path.split("/") - ext.split("/"))
  camel_path = new_path.chomp(".haml").split("/").map { |a| a.capitalize }.join.intern
  return camel_path
end

#get_modules(path, pre) ⇒ Object



114
115
116
117
118
119
# File 'lib/initializer.rb', line 114

def get_modules(path, pre)
  sub_dir_arr = path.split("/")
  sub_dir = sub_dir_arr - pre
  sub_dir_hash = sub_dir.inject({}) {|h,(k,v)| h[camel_name(k).intern] = camel_name(k) if File.extname(k) != '.rb';h}
  return sub_dir_hash
end

#instantiate_class(path, pre, extname) ⇒ Object



102
103
104
105
106
107
108
109
110
111
112
# File 'lib/initializer.rb', line 102

def instantiate_class(path, pre, extname)
  pre_arr = pre.split("/")
  Dir[path + '/*'].each do |d|
    sub_dir_hash = get_modules(d, pre_arr)
    nmodule = build_modules(sub_dir_hash)
    @sub_dir_found = load_class(d, nmodule, extname)
  end
  dir = @sub_dir_found
  @sub_dir_found = nil
  return dir      
end

#instantiate_controller(path, extname) ⇒ Object



94
95
96
97
98
99
100
# File 'lib/initializer.rb', line 94

def instantiate_controller(path, extname)
  pre = File.join(path.split("/").delete_if { |p| p == "controller" })
  dir = path.chomp("/")
  while !dir.nil? do
    dir = instantiate_class(dir, pre, extname)
  end
end

#load_class(path, nmodule, extname) ⇒ Object



139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'lib/initializer.rb', line 139

def load_class(path, nmodule, extname)
  class_before = Object.constants           # all current classes and models
  last_item = path.split("/").last
  #Dir.entries(path).each do |d|
    if File.extname(path) == extname
      require path
    elsif last_item != '.' && last_item != '..' && File.directory?(path)
      @sub_dir_found = path
    end
  #end
  # Add the new classes
  class_after = Object.constants
  new_class = class_after - class_before
  new_class.each do |c|
    klass = Object.const_get("#{c}")
    nmodule.const_set("#{c}", klass)
    Object.instance_eval{ remove_const c }
  end
  return @sub_dir_found
end

#read_configObject



58
59
60
61
62
63
64
# File 'lib/initializer.rb', line 58

def read_config
  # Convert key strings to symbols
  begin
    @system = YAML.load_file(@options[:config] + "config.yml")[@options[:env].to_s].inject({}) {|h,(k,v)| h[k.intern] =v; h}
  rescue NoMethodError
  end
end

#read_database_configObject



89
90
91
92
# File 'lib/initializer.rb', line 89

def read_database_config
  # Convert key strings to symbols
  @database = YAML.load_file(@options[:config] + "database.yml")[@options[:env].to_s].inject({}) {|h,(k,v)| h[k.intern] = v; h}
end

#set_logObject



66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/initializer.rb', line 66

def set_log
  log_path = @system[:log_path] || @options[:log_path] 
  @options[:log_path] = log_path + '/' + @options[:env].to_s + ".log"
  @options[:rotate] = !@system.nil? ? @system[:rotate] : nil
  # Set up logging
  if File.exists?(@root + "/logs")
    $logger = Logger.new(@options[:log_path], @options[:rotate])

    case @options[:env]
    when :development
      $logger.level = Logger::DEBUG
    when :test
      $logger.level = Logger::DEBUG
    when :staging
      $logger.level = Logger::DEBUG
    when :production
      $logger.level = Logger::WARN
    end

    $logger.warn("The logging level is set to #{$logger.level}")
  end
end

#set_optionsObject



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/initializer.rb', line 35

def set_options
  OptionParser.new do |opts|
    opts.banner = "Usage: lame [options] [action]"
    opts.separator ""
    opts.separator "Options:"
    opts.on("-c", "--config PATH", "Path to configuration files") {|config| @options[:config] = config}
    opts.on("-e", "--env ENVIRONMENT", "Environment to run as") {|env| @options[:env] = env.intern}
    opts.on("-d", "--daemon", "Run as a Daemon") {@options[:daemon] = true}
    opts.on("-p", "--port PORT", "Port for the server to listen on") {|port| @options[:port] = port}
    opts.on("-P", "--pid PATH", "Path to store the PID file") {|pid| @options[:pid] = pid}
    opts.on("-l", "--log PATH", "Path to log files") {|log| @options[:logs] = log}
    opts.separator ""
    opts.separator "Actions"
    opts.on("--start", "Start the server") {@options[:action] = :start}
    opts.on("--stop", "Stop the server") {@options[:action] = :stop}
    opts.on("--restart", "Restart the server") {@options[:action] = :restart}
    opts.separator ""
    opts.on("-h", "--help", "Show this help message") {puts opts; exit}
    opts.separator""
    opts.parse!
  end
end