我需要在项目的每个脚本中执行以下步骤。有没有办法避免使用Ruby复制和粘贴? parse_command_line_args
和read_app_config
是与其他模块混合的方法。
以下步骤将出现在数百个脚本中,我想保持DRY:
OPTIONS = parse_command_line_args
CONFIG = read_app_config(File.dirname(__FILE__), OPTIONS)
APP_NAME = CONFIG["APP_NAME"]
DB_CONFIG = YAML.load_file(File.expand_path('../config/database.yml', File.dirname(__FILE__)))
DB = DbManager.new(DB_CONFIG, DB_CONFIG["COLLECTION"][APP_NAME], APP_NAME)
~~~~
module CommonContants
OPTIONS = parse_command_line_args
CONFIG = read_app_config(File.dirname(__FILE__), OPTIONS)
APP_NAME = CONFIG["APP_NAME"]
DB_CONFIG = YAML.load_file(File.expand_path('../config/database.yml', File.dirname(__FILE__)))
DB = DbManager.new(DB_CONFIG, DB_CONFIG["COLLECTION"][APP_NAME], APP_NAME)
end
require 'common_contants'
include CommonContants
~~~~
parse_command_line_args
:
8: def parse_command_line_args
9- options = {}
10- OptionParser.new do |opts|
11- opts.banner = "Usage: #{self.to_s}.rb [options]"
12- opts.on('-f', '--config file path', 'config file') { |v| options[:app_cfg_fpath] = v }
13- end.parse!
14- options
15- end
read_app_config
:
17: def read_app_config(dir_path, argv=[])
18- if argv.has_key? :app_cfg_fpath
19- YAML.load_file(File.expand_path(argv[:app_cfg_fpath]), dir_path)
20- else
21- YAML.load_file(File.expand_path('./config.yml', dir_path))
22- end
23- end