Friday, June 22, 2018

How to use Redis for caching data in Rails

Why Redis is used?

This is a very basic question and it comes because you can do what redis does with postgresql for the purpose of solving the functionality aspect. What redis does is, it stores the key value pair and most of the operations can be executed in O(N) time only (for more information for every command time complexity check the redis documentation). Thus caching enables retrieval of data at much higher speeds and is optimal for tasks such as pub/sub and queries that need quicker access. 

Redis Configuration 

Initialization - redis/config/ini_redis.rb
redis_host = Rails.application.secrets.redis && Rails.application.secrets.redis['host'] || 'localhost'
redis_port = Rails.application.secrets.redis && Rails.application.secrets.redis['port'] || 6379

# The constant below will represent ONE connection, present globally in models, controllers, views etc for the instance. No need to do everytime
REDIS = redis_host, port: redis_port.to_i)

model.rb file - models/user.rb

def online?
You can use views such as like this, views/users/show.html.erb
@users_ol = User.where(:id => @id).select(&:online?)

Thursday, June 14, 2018