Search code examples
ruby-on-railsdelayed-jobamazon-elastic-beanstalkebextensions

warning: already initialized constant within config/routes.rb


I have the following class within config/routes.rb. When I deploy the application via Elastic Beanstalk with an .ebextensions file including a post-deploy script to start delayed_job I receive:

...
warning: already initialized constant DistributionSlugConstraint::MATCH_REGEX
warning: previous definition of MATCH_REGEX was here
delayed_job: running [pid 14867]
...

Class within config/routes.rb.

class DistributionSlugConstraint
  MATCH_REGEX = /B[a-zA-Z1-9_]{5}/
  def self.matches?(request)
    request.fullpath =~ MATCH_REGEX
  end
end

Rails.application.routes.draw do

  constraints(DistributionSlugConstraint) do
    get "/:slug" => "distributions#show", as: :distribution
  end

end

Solution

  • There are a number of reasons why this error may be happening, but a fix would be to not declare the constant. Not sure it you're using DistributionSlug::MATCH_REGEX elsewhere in your code, but if you aren't, you can do:

    class DistributionSlugConstraint
      def self.matches?(request)
        request.fullpath =~ /B[a-zA-Z1-9_]{5}/
      end
    end
    

    If you are using it elsewhere in your code you could make it a class method and call that instead of the constant. Another route to go might be to declare it as a configuration in application.rb

    I've seen this kind of thing pop up when using a multi-threaded app server like puma, or in Sidekiq jobs. Hard to say more without knowing more about your infrastructure.