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!
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.
irb
session, and assign$foo = 1
in one and try toputs $foo
in other. - Зелёный