Saturday, December 15, 2012

Memcached with Ruby on rails


How to use Memcached in a Rails application

Caching is one of the techniques used for improving the overall performance of a web site. One of the most common servers for caching is memcached.

Installation

To install memcached server in Ubuntu use following command in terminal:

 sudo apt-get install memcached
 sudo apt-get install libmemcached-dev libmemcached-tools

Start, stop and restart memcached service

 sudo /etc/init.d/memcached start 
 sudo /etc/init.d/memcached stop
 sudo /etc/init.d/memcached restart

Configuring a Rails App to use memcached

Add the following Gem to yout Gemfile
 
gem 'dalli'
gem 'kgio'
Dalli is the gem used for comunicating with memcached and kgio improves the read/write performance. After editing the Gemfile we run bundle install command in the terminal.
Now that you have the gems installed, you need to tell rails to use it.

Configuring a Rails App environment file

In production.rb and development.rb, staging.rb, set the cache_store :

 # /config/environments/production.rb
 config.cache_store = :dalli_store
# /config/environments/development.rb
config.cache_store = :dalli_store

# /config/environments/staging.rb
config.cache_store = :dalli_store

Now change your session initializer (for memcache session support)

 # config/initializers/session_store.rb

require 'action_dispatch/middleware/session/dalli_store' YOURAPPNAMEHERE::Application.config.session_store :dalli_store

Testing if all is well

Open a rails console and test setting a value and after getting the same value.

$ rails c
 
> require 'dalli'
> ca = Dalli::Client.new('localhost:11211')
> ca.set('naim', 123)
> value = dc.get('naim') 

References:

  1. Memcached
  2. Dalli
  3. kgio

Sunday, June 24, 2012

How to remove index.php from Codeigniter URL

In codeignetor, your apps url include with index.php by default. Like as : 
http://naimrajib.blogspot.com/index.php/[controller-class]/[controller-method]/
But you can easily remove index.php from your CodeIgniter’s URL so that your URL should be like:
http://naimrajib.blogspot.com/[controller-class]/[controller-method]/

To do this just follows the following steps:
  1. Open config.php from system/application/config directory and replace
    $config['index_page'] = “index.php” by   $config['index_page'] = “”

  2. Create a “.htaccess” file in the root of CodeIgniter directory (where the system directory resides).

  3. open the ".htaccess" file using your favorite text editor, write down the following script and save it:
RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA] 

  1. In some case the default setting for uri_protocol does not work properly.
To solve this problem just replace
$config['uri_protocol'] = “AUTO” by
$config['uri_protocol'] = “REQUEST_URI”

from system/application/config/config.php