How to access rails cache inside rack middlware

263 views Asked by At

I have some custom middleware that is include at the top of my stack and what i need to do in it is access the rails cache. How can I load/access the rails cache from the middleware without having to load the whole rails app up first?

2

There are 2 answers

0
Sam On BEST ANSWER

Rails on Rack Rails Application's Rack Object

ApplicationName::Application is the primary Rack application object of a Rails application. Any Rack compliant web server should be using ApplicationName::Application object to serve a Rails application. Rails.application refers to the same application object. rails server

rails server does the basic job of creating a Rack::Server object and starting the webserver.

Here's how rails server creates an instance of Rack::Server

Rails::Server.new.tap do |server|
  require APP_PATH
  Dir.chdir(Rails.application.root)
  server.start
end

The Rails::Server inherits from Rack::Server and calls the Rack::Server#start method this way:

class Server < ::Rack::Server
  def start
    ...
    super
  end
end

Here's how it loads the middlewares:

def middleware
  middlewares = []
  middlewares << [Rails::Rack::Debugger] if options[:debugger]
  middlewares << [::Rack::ContentLength]
  Hash.new(middlewares)
end

courtsy : http://guides.rubyonrails.org/rails_on_rack.html and also u can follow : https://devcenter.heroku.com/articles/rack-cache-memcached-rails31

0
Alex Siri On

I just did a test, and

Rails.cache.fetch('test') { 'A test' }

inside of a custom middleware, and it worked just fine.

Can you try that?