Search code examples
ruby-on-railsruby-on-rails-7

Rails: code runs in irb, NoMethodFound in initializer


I’ve installed the ‘faye’ gem and have the following code in config/initializers/faye.rb:

require 'faye'

Faye::WebSocket.load_adapter('puma')

faye_server = Faye::RackAdapter.new(:mount => '/faye', :timeout => 45)
Rails.application.config.middleware.insert_before Rack::Runtime, faye_server

When trying to start the server, I get this:

undefined method 'new' for an instance of Faye::RackAdapter (NoMethodError)

However, I can run irb and then the above lines of code without issues - clearly getting back an instance of Faye::RackAdapter after calling ‘new’.

I suspect I don’t understand something about initializers, but searching didn’t turn up anything obvious. What am I missing?


Solution

  • You need to pass class as an argument:

    require "faye"
    
    Faye::WebSocket.load_adapter("puma")
    
    Rails.application.config.middleware.insert_before(
      Rack::Runtime,
      Faye::RackAdapter, mount: "/faye", timeout: 45
    )
    

    https://guides.rubyonrails.org/rails_on_rack.html#adding-a-middleware


    You should look at your stack trace, because the error is not coming from your initializer:

    /home/alex/.rbenv/versions/3.3.0/lib/ruby/gems/3.3.0/gems/actionpack-7.1.3/lib/action_dispatch/middleware/stack.rb:42:in `build':
    undefined method `new' for an instance of Faye::RackAdapter (NoMethodError)
    
            klass.new(app, *args, &block)
                 ^^^^