Search code examples
ruby-on-railsnamespacesrake

Uninitialized constant error when trying to refer to a database record within a service


I'm trying to create a rake task that uses a service. Within that service, I want to load the last saved record of a MonthlyMetrics table within my database.

Within my rake file:

require 'metrics_service'
namespace :metrics do
  @metrics_service = MetricsService.new

  task :calculate_metrics => [:check_for_new_month, :update_customers, :update_churn, :do_more_stuff] do
    puts "Donezo!"
  end

  # ...more cool tasks

end

And my MetricsService within lib/metrics_service.rb:

class MetricsService

  def initialize
    @metrics = MonthlyMetric.last
    @total_customer_count = total_customers.count
    assign_product_values
  end

  # Methods to do all my cool things...

end

Whenever I try to run something like rake:db:migrate, I get the following error:

NameError: uninitialized constant MetricsService::MonthlyMetric

I'm not sure why it's trying to refer to MonthlyMetric the way it is... As a class within the MetricsService namespace..? It's not like I'm trying to define MonthlyMetric as a nested class within MetricsService... I'm just trying to refer to it as an ActiveRecord query.

I've done other ActiveRecord queries, for example User, in other services within the same directory.

What am I doing wrong here?


Solution

  • I think if you just add => :environment to the end of your rake task, that may fix the problem.

    As in:

    task :calculate_metrics => [:check_for_new_month, :update_customers, :update_churn, :do_more_stuff] => :environment do

    I've run into similar problems where Rails does not initialize the correct environment without this tacked on to each rake task.