我怎么能在每个脚本中运行相同的代码?

时间:2015-06-25 05:41:23

标签: ruby

我需要在项目的每个脚本中执行以下步骤。有没有办法避免使用Ruby复制和粘贴? parse_command_line_argsread_app_config是与其他模块混合的方法。

以下步骤将出现在数百个脚本中,我想保持DRY:

sample_1.rb(之前)

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)
~~~~

common_contants.rb

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

sample_1.rb(之后)

    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

1 个答案:

答案 0 :(得分:1)

您应该将代码的这一部分转换为module并将其转换为您需要的地方。

  

当你开始编写越来越大的Ruby程序时,你就会   自然而然地发现自己会产生大量可重复使用的代码---库   通常适用的相关例程。你想要的   将此代码分解为单独的文件,以便共享内容   不同的Ruby程序之间。通常这个代码将被组织成   课程,所以你可能会坚持一个班级(或一组相互关联的   类)到文件中。但是,有时您想要分组   不能自然形成课堂的事物。

     

答案是模块机制。模块定义命名空间,a   沙盒,您的方法和常量可以在其中播放而不必   担心被其他方法和常量踩到。

了解更多herehere