0

I would like to user Redis in my Sinatra app. Though I can access Redis instance in the console on local and remote (heroku), when I want to use it in a rake task, an error is triggered and I don t seem to get why is that.

app.rb:

class MyApp < Sinatra::Base
  configure do
    uri = URI.parse(ENV["REDISCLOUD_URL"])
    $redis = Redis.new(:host => uri.host, :port => uri.port, :password => uri.password)
  end
end

config.ru:

require 'rubygems'
require 'sinatra'
require './app'
run MyApp

Gemfile

gem 'redis'

Rakefile.rb

desc 'Try Redis'
  task :try_redis do
  puts $redis.set("try", 0)
end

rake aborted! NoMethodError: undefined method `set' for nil:NilClass

I am not really used to Sinatra, and nothing looks particularly wrong to me. I do not understand why my global variable $redis would not be accessible from everywhere in my app...

If you can enlighten me, thank you by advance!

1 답변


1

I do not understand why my global variable $redis would not be accessible from everywhere in my app

Your rake task is not related to your app. The $redis variable available only when you run sinatra server and not available when you run your rake task. The rake task run in own thread.


  • Thank you, I am still a bit confused about that("Your rake task is not related to your app."), but I just have to move the connexion to Redis into the rake task and it works fine. Your answer helped me to move forward, thank you very much! - user3029400
  • Your rake task is not related to your app. I mean on the code level, your server and a rake task not connected, it's a different thread. - Зелёный
  • open two irb session, and assign $foo = 1 in one and try to puts $foo in other. - Зелёный
  • I see. They are 2 different threads, both should have a connexion to the same redis DB to be able to get the data. It makes sense. Thanks! - user3029400

Related

Latest