ElasticSearch Rails 3 Part 1

add to Gamefile

gem 'tire'

articles_controller.rb

def index
  @articles = Article.search(params)
end

models/article.rb

include Tire::Model::Search
include Tire::Model::Callbacks

def self.search(params)
  tire.search(load: true) do
    query { string params[:query], default_operator: "AND" } if params[:query].present?
    filter :range, published_at: {lte: Time.zone.now}
  end
end

articles/index.html.erb

<%= form_tag articles_path, method: :get do %>
  <p>
    <%= text_field_tag :query, params[:query] %>
    <%= submit_tag "Search", name: nil %>
  </p>
<% end %>

Sortable List in Ruby on Rails 3 Using jQuery

1. Go to Gamefile

gem "rails"
gem "mysql2"
gem "acts_as_list"

# go to console:
$ bundle install

Add acts_as_list to model

class Book < ActiveRecord::Base
  acts_as_list
end

add jquery to view and setup javascript content_for, Go to app/views/layouts/books.html.erb
Change this:

<%= javascript_include_tag :defaults %>

To this:

<%= javascript_include_tag "https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js", "https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/jquery-ui.min.js", "rails.js" %>

Also before /body add:

<%= yield :javascript %>

edit index for li – tables don’t work

<h1>Listing books</h1>
<ul id="books"> <% @books.each do |book| %>
  <li id="book_<%= book.id %>"><span class="handle">[drag]</span><%= book.name %></li>
<% end %></ul>
<%= link_to 'New book', new_book_path %>

add javascript in view

# index.html.erb
<% content_for :javascript do %>
<%= javascript_tag do %>
// Sorting the list

$(document).ready(function(){
   $('#books').sortable({
       axis: 'y',
       dropOnEmpty: false,
       handle: '.handle',
       cursor: 'crosshair',
       items: 'li',
       opacity: 0.4,
       scroll: true,
       update: function(){
          $.ajax({
              type: 'post',
              data: $('#books').sortable('serialize'),
              dataType: 'script',
              complete: function(request){
                 $('#books').effect('highlight');
              },
                 url: '/books/sort'})
              }
          });
     });
 });
     <% end %>
<% end %>

and your controller

def index
   @books = Book.order('books.position ASC')
end

def sort
   @books = Book.all
   @books.each do |book|
   book.position = params['book'].index(book.id.to_s) + 1
   book.save
end

render :nothing => true
end

update your routes

root to: "books#index"
resources :books do
   post :sort, on: :collection
   # ruby 1.8 would go :on => :collection
end

How to Create Ajax Pagination using CodeIgniter?

CodeIgniter has many built-in classes and plugins. Pagination class of CodeIgniter is very easy and simple to use. Also Ajax Pagination library is availanle in Codeigniter. Here i will describe how to create simple ajax pagination in Codeigniter using some simple steps.

First of all download Ajax Pagination from Codeigniter site. And put this library in “system/libraries/” folder.
Along with library you need to download prototype.js file and put this file any where on root.
Here we have a table which we use for getting records and apply pagination on its records.

CREATE TABLE `my_best_friends` (
  `f_id` int(11) NOT NULL auto_increment,
  `f_name` varchar(100) NOT NULL,
  `f_phone` int(11) NOT NULL,
  `f_email` int(11) NOT NULL,
  `f_address` int(11) NOT NULL,
  PRIMARY KEY  (`f_id`)
)

Your controller:

class Paging extends Controller {
 
	function Paging(){
 
		parent::Controller();
		$this->load->helper(array('form','url'));
		$this->load->helper('text');
		$this->load->library('Ajax_pagination');
	}
 
	function index()
	{
		redirect ('paging/my_friends');
	}
 
	function my_friends()
	{
		$pdata['TotalRec'] 	= $this->FriendsModel->TotalRec();
		$pdata['perPage'] 	= $this->perPage();
		$pdata['ajax_function']	= 'get_friends_ajax';
 
		$subdata['paging'] 	= $this->parser->parse('paging', $pdata, TRUE);
		$subdata['all_friends'] 	= $this->FriendsModel->my_friends($this->perPage());
 
		$data['body_content'] 	= $this->parser->parse('friend_list', $subdata, TRUE);	
 
		$this->load->view('main',$data);
	}
 
	function get_friends_ajax()
	{
             $pdata['TotalRec'] = $this->FriendsModel->TotalRec();
             $pdata['perPage']  = $this->perPage();
 
	     $pdata['ajax_function'] =  'get_friends_ajax';
 
	     $data['paging'] =  $this->parser->parse('paging', $pdata, TRUE);
	     $data['all_friends'] = $this->FriendsModel->my_friends($this->perPage());
 
	     $this->load->view('friend_list',$data);
	}
 
	function PerPage()
	{
		return 5;
	}
 
}

Model :

class FriendsModel extends Model
{
    function FriendsModel()
    {
		parent::Model();
	}
 
	function TotalRec()
	{
	  $sql = "SELECT * FROM my_friends";
          $q = $this->db->query($sql);
          return $q->num_rows();
       }
 
	function my_friends($perPage)
	{
		$offset = $this->getOffset()
		$query ="SELECT * FROM  my_friends Order By f_id Desc LIMIT ".$offset.", ".$perPage;
		$q = $this->db->query($query);
		return $q->result();
	}
 
	function getOffset()
	{
        $page = $this->input->post('page');
        if(!$page):
        $offset = 0;
        else:
        $offset = $page;
        endif;
        return $offset;
    }
}

View: paging.php in application/views/ folder

$config['first_link'] 	= 'First';
$config['div'] 		= 'container'; //Div tag id
$config['base_url'] 	= base_url().'paging/'.$ajax_function;
$config['total_rows']	= $TotalRec;
$config['per_page'] 	= $PerPage;
$config['postVar'] 	= 'page';
 
$this->ajax_pagination->initialize($config);
echo $this->ajax_pagination->create_links();

View: friend_list.php in application/views/ folder

<table border="1" width="200">
<tbody>
<tr>
<td>Friend Name</td>
<td>Friend Phone</td>
<td>Friend Address</td>
</tr>
foreach($all_friends as $row)
 {
<tr>
<td>echo $row->f_name</td>
<td>echo $row->f_phone</td>
<td>echo $row->f_address</td>
</tr>
}</tbody>
</table>

Main home file: main.php in application/views/ folder
This file contains your html code and all css and js files.
I have just given main container where your data will show. you have to add html and css/js files your self.

<div id="container">
     echo @$body_content;</div>

Rails Page Caching

1 Basic Caching

This is an introduction to the three types of caching techniques that Rails provides by default without the use of any third party plugins.

To start playing with caching you’ll want to ensure that config.action_controller.perform_caching is set to true, if you’re running in development mode. This flag is normally set in the corresponding config/environments/*.rb and caching is disabled by default for development and test, and enabled for production.

config.action_controller.perform_caching is set to true

1.1 Page Caching

Page caching is a Rails mechanism which allows the request for a generated page to be fulfilled by the webserver (i.e. Apache or nginx), without ever having to go through the Rails stack at all. Obviously, this is super-fast. Unfortunately, it can’t be applied to every situation (such as pages that need authentication) and since the webserver is literally just serving a file from the filesystem, cache expiration is an issue that needs to be dealt with.

To enable page caching, you need to use the caches_page method.

class ProductsController < ActionController
 
  caches_page :index
 
  def index
    @products = Products.all
  end
end

Let’s say you have a controller called ProductsController and an index action that lists all the products. The first time anyone requests /products, Rails will generate a file called products.html and the webserver will then look for that file before it passes the next request for /products to your Rails application.

By default, the page cache directory is set to Rails.public_path (which is usually set to the public folder) and this can be configured by changing the configuration setting config.action_controller.page_cache_directory. Changing the default from public helps avoid naming conflicts, since you may want to put other static html in public, but changing this will require web server reconfiguration to let the web server know where to serve the cached files from.

The Page Caching mechanism will automatically add a .html extension to requests for pages that do not have an extension to make it easy for the webserver to find those pages and this can be configured by changing the configuration setting config.action_controller.page_cache_extension.

In order to expire this page when a new product is added we could extend our example controller like this:

class ProductsController < ActionController
 
  caches_page :index
 
  def index
    @products = Products.all
  end
 
  def create
    expire_page :action => :index
  end
 
end

If you want a more complicated expiration scheme, you can use cache sweepers to expire cached objects when things change. This is covered in the section on Sweepers.

Nested Form For Rails 3

Setup

Add it to your Gemfile then run bundle to install it.

gem "nested_form"

Next run the generator to create the JavaScript file. This will automatically detect if you are using jQuery or Prototype.

rails g nested_form:install

Running the generator will add a file at public/javascripts/nested_form.js which should be included after the jQuery or Prototype framework.

<%= javascript_include_tag :defaults, "nested_form" %>

Usage

Imagine you have a Project model that has_many :tasks. To be able to use this gem, you’ll need to add accepts_nested_attributes_for :tasks to your Project model. If you don’t have the accepts_nested_attributes_for :tasks you’ll get a Missing Block Error.

This will create a tasks_attributes= method, so you may need to add it to the attr_accessible array. (attr_accessible :tasks_attributes)

Then use the nested_form_for helper method to enable the nesting.

<%= f.fields_for :tasks do |task_form| %>
  <%= task_form.text_field :name %>
  <%= task_form.link_to_remove "Remove this task" %>
<% end %>
<p><%= f.link_to_add "Add a task", :tasks %></p>

jQuery: Set time interval between events with queue function

You can use jQuery queue() function with setTimeout() function to set some time interval between events in jQuery. Like, you have run one event and wanted the browser to wait for some time to run the next event. At this instance, queue function is very helpful.

Suppose, you wanted an image to fade in and out. You can use fadeIn() and fadeOut() jQuery functions to do so. But when you like to wait for some time between fade in and fade out then you can use the queue() function. Remember that, .dequeue() is necessary to write in a queue() so that the next function in line executes.

<html>
<head>
<title>jQuery: Queue</title>
<script src="jquery-1.4.min.js" type="text/javascript"></script>
<script type="text/javascript">
    $(function(){
        var img = $(".img");
        for(var i=0;i<4;i++) {
            img.queue(function(){
                setTimeout(function(){
                    img.dequeue();
                }, 1000);
            });
 
            img.fadeOut("slow");
 
            img.queue(function(){
                setTimeout(function(){
                    img.dequeue();
                }, 1000);
            });
 
            img.fadeIn("slow");
        }
    });
</script>
</head>
<body>
<div align="center">
    The image will fade in and out for 5 times.<br/>
    <img class="img" src="hills.jpg" alt="image" />
</div>
</body>
</html>

Facebooker2 using Mogli request

Provides rails helpers for interfacing with Facebook’s OpenGraph Javascript API.

Example

1. You need a facebook app. Have your API Key, Application Secret, and Application ID handy.
2. Add to your Gemfile

gem 'facebooker2'
gem 'mogli'

3. Create config/facebooker.yml with the appropriate environment.

production:
  app_id: <your application id>
  secret: <your application secret>
  api_key: <your application key>

4. Create config/initializers/facebooker2.rb and place the following line in it

Facebooker2.load_facebooker_yaml

5. Add the following line to your app/controllers/application_controller.rb add it right after the line class

class ApplicationController < ActionController::Base
  include Facebooker2::Rails::Controller

def post_to_my_wall(msg, picture)
    current_facebook_user.feed_create(Mogli::Post.new(
        :message => "#{msg}",
        :picture => "#{picture}"
      ))
  end

  def post_to_friend_wall(uid, msg, picture)
    client = current_facebook_client   

    friend = Mogli::User.find(uid, client, link)
    friend.feed_create(Mogli::Post.new(
        :message => "#{msg}",
        :picture => "#{picture}",
        :link => "#{link}"
      ))
  end
end

6. for Authenticator user Install Facebooker2 for Rails 3