[Redis] Setup redis with Rails

  1. Install Gemfile
    gem 'redis'
    gem 'redis-namespace'
  2. Create file config: redis.yml
    development:
       host: hdev01
       port: 6479
       db: 0
       namespace: 4travel
  3. Create function for load file config
    def redis_config
      @redis_config ||= YAML.load(File.open(Rails.root.join("config/redis.yml"))).symbolize_keys[Rails.env.to_sym].symbolize_keys
    end
  4. Create namspace redis with function config

    def redis
      @redis ||= Redis::Namespace.new(redis_config[:namespace], :redis => Redis.new(redis_config))
    end
  5. Use redis to set and get data

    #set data
    redis.set(key, value, ex: expiration_time)
    
    #get data
    redis.keys('*').grep(...) # get all keys and use grep to filter
Advertisements

[Rails] Check request is_bot or not

def is_bot?(request)
 agent = request.env["HTTP_USER_AGENT"]
 # agent = request.user_agent
 matches = nil
 matches = agent.match(/(facebook|postrank|voyager|twitterbot|googlebot|slurp|butterfly|pycurl|tweetmemebot|metauri|evrinid|reddit|digg)/mi) if agent
 if ( agent.nil? or matches)
   return true
 else
   return false
 end
end

Another code:

def is_bot?
  http_user_agent = request.env["HTTP_USER_AGENT"] || ""

  begin
    ua = ""
    ua = URI.decode(http_user_agent)
  rescue
  end

  browser = Browser.new(ua: ua)
  return browser.bot?
end

Example:

1 example Googlebot smartphone user-agent

Mozilla/5.0 (Linux; Android 6.0.1; Nexus 5X Build/MMB29P) 
AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.96 
Mobile Safari/537.36 (compatible; Googlebot/2.1; +
http://www.google.com/bot.html)

We use agent.match(/(facebook|twitterbot|googlebot)/mi), it will search in user-agent string, find text match googlebot. 

/mi: search downcase and upcase

without /mi: search exactly with googlebot (Googlebot is not match)