ruby-on-rails – 在rake任务中需要lib

我在lib / models / alert_import’中有一个文件alert_import,我想在我的任务中使用……这样:
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

在这代码中我得到错误

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

在AlertImport我有

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导入文件,然后将模块包含在命名空间中.这是它的样子:
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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...