Вопрос

Я настраиваю серию пользовательских задач rake для проекта, который я создаю, с интервалом между именами.Эти задачи можно просмотреть, выполнив rake tasks с консоли.

desc 'List all available placewise rake tasks for this application.'
task :tasks do
    result = %x[rake -T | sed -n '/placewise:/{/grep/!p;}']
    result.each_line do |task|
            puts task
    end
end

Все эти задачи хранятся в lib/tasks/placewise и построен вот так:

namespace :placewise do
    namespace :db do
    desc "Drop and create the current database, the argument [env] = environment."
    task :recreate, [:env] do |t,args|
            env = environments(args.env)
            msg("Dropping the #{env} database")
            shell("RAILS_ENV=#{env} rake db:drop", step: "1/3")
            msg("Creating the #{env} database")
            shell("RAILS_ENV=#{env} rake db:create", step: "2/3")
            msg("Running the #{env} database migrations")
            shell("RAILS_ENV=#{env} rake db:migrate", step: "3/3")
    end
  end
end

Новая задача, например, может начинаться с базовой настройки следующим образом:

namespace :placewise do
    namespace :example do
    desc "example"
    task :example do

    end
  end
end

Как вы можете видеть, namespace :placewise do будет реплицироваться каждый раз.Я хочу сохранить все наши пользовательские задачи rake в одной группе, однако мне любопытно, есть ли способ избежать необходимости добавлять это пространство имен к каждой из них .rake файл?

Ваше здоровье.

Это было полезно?

Решение

К сожалению, мне посоветовали отказаться от этой стратегии, и в процессе поиска я обнаружил, что мои вспомогательные методы были настроены неправильно.Итак, поехали.

Я создал новую папку modules в lib/modules с новым helper_functions.rb файл внутри этого каталога.Вот мои помощники:

вспомогательные функции модуля

    # ------------------------------------------------------------------------------------
    # Permitted environments
    # ------------------------------------------------------------------------------------
    def environments(arg)
        arg = arg || "development"
        environments = ["development", "test", "production"]
        if environments.include?(arg)
            puts
            msg("Environment parameter is valid")
            return arg
        else
            error("Invalid environment parameter")
            exit
        end
    end
    # ------------------------------------------------------------------------------------
    # Console message handler
    # ------------------------------------------------------------------------------------
    def msg(txt, periods: "yes", new_line: "yes")
        txt = txt + "..." if periods == "yes"
        puts "===> " + txt
        puts if new_line == "yes"
    end
    def error(reason)
        puts "**** ERROR! ABORTING: " + reason + "!"
    end
    # ------------------------------------------------------------------------------------
    # Execute Shell Commands
    # ------------------------------------------------------------------------------------
    def shell(cmd, step: nil)
        msg("Starting step #{step}", new_line: "no") if step.present?
        if ENV['TRY']
            puts "-->> " + cmd
        else
            sh %{#{cmd}}
        end
        msg("#{step} completed!", periods: "no")
    end
end

Затем в Rakefile Добавить:

# Shared Ruby functions used in rake tasks
require File.expand_path('../lib/modules/helper_functions', __FILE__)
include HelperFunctions

Rails.application.load_tasks

# Do not add other tasks to this file, make files in the primary lib/tasks dir ending in .rake
# All placewise tasks should be under the lib/tasks/placewise folder and end in .rake
desc 'List all available placewise rake tasks for this application.'
task :tasks do
    result = %x[rake -T | sed -n '/placewise:/{/grep/!p;}']
    result.each_line do |task|
            puts task
    end
end

И, наконец, мой .rake задачи выглядят следующим образом:

namespace :placewise do
# ------------------------------------------------------------------------------------
    namespace :db do
        # ------------------------------------------------------------------------------------
    desc "Drop and create the current database, the argument [env] = environment."
    task :recreate, [:env] do |t,args|
            env = HelperFunctions::environments(args.env)
            HelperFunctions::msg("Dropping the #{env} database")
            HelperFunctions::shell("RAILS_ENV=#{env} rake db:drop", step: "1/3")
            HelperFunctions::msg("Creating the #{env} database")
            HelperFunctions::shell("RAILS_ENV=#{env} rake db:create", step: "2/3")
            HelperFunctions::msg("Running the #{env} database migrations")
            HelperFunctions::shell("RAILS_ENV=#{env} rake db:migrate", step: "3/3")
    end
        # ------------------------------------------------------------------------------------
  end
# ------------------------------------------------------------------------------------
end
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top