在 rake 任务中需要 lib [英] require lib in rake task

查看:38
本文介绍了在 rake 任务中需要 lib的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 lib/models/alert_import' 中有一个文件 alert_import,我想在我的任务中使用这样的:

I have a file alert_import in lib/models/alert_import', I would like to use in my task sth like this:

task :send_automate_alerts => :environment do
 # STDERR.puts "Path is #{$:}"
  Rake.application.rake_require '../../lib/models/alert_import'
  ai = AlertImport::Alert.new(2)
  ai.send_email_with_notifcations
end

在这段代码中我得到错误:

In this code I get error:

找不到../../lib/models/alert_import

Can't find ../../lib/models/alert_import

在 AlertImport 我有:

in AlertImport I have:

module AlertImport

  class Alert

    def initialize(number_days)
      @number_days = number_days
    end

    def get_all_alerts
      alerts = { }
      Organization.automate_import.each do |o|
        last_import = o.import_histories.where(import_type: "automate").last
        last_successful_import = ImportHistory.last_automate_successful_import(o)
        if last_import
          if last_import.created_at + @number_days.days >= Time.now
            alerts[o.id] ="Error during last automate import Last successful import was #{ last_successful_import ? last_successful_import.created_at : "never"}" if last_import.status == "failure"
            alerts[o.id] ="Error during last automate import - status pending Last successful import was #{ last_successful_import ? last_successful_import.created_at : "never"}" if last_import.status == "pending"
          else
            alerts[o.id] = "There were no new files uploaded within #{@number_days} days"
          end
        else
          alerts[o.id] = "The import was never triggered at all"
        end
      end
      alerts
    end

    def send_email_with_notifcations
      alerts =get_all_alerts
      unless alerts.empty?
        AlertMailer.email_notifications(alerts).deliver
      end
    end

  end

end

正确的解决方法是:

desc "Send alerts about automate imports"

task :send_automate_alerts => :environment do
  require "#{Rails.root}/lib/models/alert_import"
  ai = AlertImport::Alert.new(2)
  ai.send_email_with_notifcations
end

推荐答案

在 Rails 3.x 中,我通过首先使用 require 导入文件然后将模块包含到命名空间中取得了成功.这是它的外观:

In Rails 3.x, I've had success by first importing the file using require and then including the module to the namespace. Here's how it would look:

require 'models/alert_import'

namespace :alerts

  include AlertImport

  desc 'Send alerts about automate imports'
  task send_automate_alerts: :environment do
    ai = AlertImport::Alert.new(2)
    ai.send_email_with_notifcations
  end

end

这篇关于在 rake 任务中需要 lib的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆