Tuesday, November 11, 2014

Rails Active model serializers

When to use active model serializer ?

    When you have your app running on both browser and mobile app, and if you have a backend rails server then active model serialiser is a perfect gem for serving api’s.

There are other gems like rabl but I personally prefer this gem because this is extremely easy to use and it has lot of + points.


Step 1.

    Add gem into your Gemfile

    gem ‘active_model_serializers'


Step 2.

    Create a serializer file by running

    rails g serializer user


    which will create  app/serializers/user_serializer.rb



Step 3.

    In serializer, you can add attributes, associations, custom methods.

    attributes :id, :name, :followers, :timestamp


So here id and name are user fields. Followers is an association in user. timestamp is a custom method.

You can define that method like this.

    def timestamp
        object.created_at.strftime(“%B %d %Y”)
    end       

Step 4.

    In your controller, you probably would have added

        respond_to :json, :html 
    and in action

        respond_with @user

When you visit /users/1.json
   
{

    "user": {
        "id": 1,
        "email": "foodoo@example.com",
        "name": "Foo doo",
        "microposts": [
            {
                "id": 1,
                "content": "This is a micropost",
                "user_id": 1,
                "created_at": "2014-11-11T16:11:08.500Z",
                "updated_at": "2014-11-11T16:11:08.500Z"
            }
        ],
        "followers": [ ]
    }

}

Saturday, April 26, 2014

Multiple solr's in single solr instance

Step 1:

Go to your solr directory.
cd /opt/solr141/
sudo mkdir home1
copy contents into home1 directory from other home directory.
sudo cp -a /opt/justbooks/solr141/home/. /opt/justbooks/solr141/home1

Step 2:

create solr1.xml under tomcat6/conf/catalina/localhost. (<your url>/solr1) Copy from solr.xml and just change value to point to new home dir in environment tag
 
<Context docBase="/opt/solr/solr141/dist/apache-solr-1.4.1.war" debug="0" crossContext="true" > <Environment name="solr/home" type="java.lang.String" value="/opt/solr/solr141/home1" override="true" /> </Context>

Step 3:

In
/opt/solr/solr141/home1/conf/Solr-config.xml 
<dataDir>${solr.data.dir:/opt/solr/solr141/home2/data}</dataDir> <locktype>simple</locktype> <unlockonstartup>true</unlockonstartup>

Step 4:

Restart tomcat

Step 5:

Since we copied from other home folder, we need to clean up the index
curl localhost:7585/solr3/update --data '*:*' -H 'Content-type:text/xml; charset=utf-8'

Friday, March 14, 2014

Fetch records from sql query - Ruby On Rails - Oci8 cursor

Let's say we need to fetch the records from this sql query in rails.
  
s = ActiveRecord::Base.connection.execute("select id, email from users" )

The output will be something like
  
  < OCI8::Cursor:0xf73ac30 >

which is nothing but a cursor object. But how to read the records from this cursor?.
The code to fetch the record is
  
while r = s.fetch_hash
   puts s
end
The output will be
  
{"ID"=>10005, "EMAIL"=>"2@gmail.com"}
{"ID"=>10006, "EMAIL"=>"3@gmail.com"}
{"ID"=>10002, "EMAIL"=>"1@gmail.com"}

Monday, October 15, 2012

Find type of the request in controller

Is there any way to find the type of request in controller ?

 Yes.

What we do in routes.rb is , define the type of request to particular action .

But What If we want to find out the type of request in controller .


if request.get?
   logger.info "Request is GET"
elsif request.post?
   logger.info "Request is POST"
elsif request.xhr?
   logger.info "Request is AJAX"
end


Thursday, October 11, 2012

Ajax Request in Ruby On Rails (UJS)



Many programmer uses jquery to catch click event and do $.get or $.post to access the server and print the response in a required div.

But there is a handy way to do ajax request using UJS provided by Rails .

Let us take an example of flipkart "add to wish list" event. So In flipkart.com when you click add to wish list , the item will be added in your wishlist .

This can be easily achieved in three easy steps.
Now lets see how to do that in rails using UJS

Step 1:
In view(show.haml.html) your may have
  
= link_to "Add to wishlist" , wish_list_path(@product) ,:id => "wish_list_link" 


Now we make it as ajax request by adding :remote => true
  
= link_to "Add to wishlist" , wish_list_path(@product) ,:id => "wish_list_link"  , 
:remote => true

Step 2:
Now in controller
    
    def wish_list
      #adding wish list 
      respond_to do |format|
         format.js #This line is important
       end
    end 
    


Step 3:
Now create a file named wish_list.js.erb
  
    $("#wish_list_link").html(''added to wishlist");
     # Lets say you want to render a partial .
    $("#wish_list_linkt").html('<%= escape_javascript(render :partial => "wish_list" , :locals => { :product => @product})%>');


Step 4(optional):
You can use jquery to show the loading part while server is responding
  
   $("#wish_list_link").live("click",function(){
        #show_loading_img
   })


...and that's it.

Monday, July 2, 2012

Rubber + EC2 + Rails + Oracle + nginx + Passenger



Deploying rails app into EC2 using Rubber
=================================

Step 1 
------
Get the key from aws and store it in ~/.ec2 folder  

         chmod 400 keyname

Generate the publickey     

         ssh-keygen -y -f keyname > keyname.pub

Step 2
------
Add rubber gem in your gemfile

        gem rubber

and do 

         bundle install

Step 3
------
Now do vulcanize. Am using nginx and passenger 

        rails g vulcanize minimal_passenger_nginx

Step 4
--------
Now edit following fields in config/rubber/rubber.yml

       access key
       secret access key
       account name
       app name
       app user
       image id
       image type

Step 5 : 
--------
Deploy Part :
  
       cap rubber:create
       cap rubber:bootstrap 
       cap deploy

If you are using oracle instant client set the environment variable in server and then do 'cap deploy'


Here is the way to bypass fingerprint authentication prompt : 
add these two lines in deploy script. 

ssh_options[:keys] = [File.join(ENV["HOME"], ".ssh", "id_rsa")] 
set :deploy_to, "your_deploy_folder"

 


          



   

Monday, March 19, 2012

Follow Me

         This post is all about google reader.If you are a regular blog reader you might know about google reader tool.If you dont know about that you can continue reading.

 
 
Roughly am following 50 blogs.So whenever some one posts, google reader updates automatically and fetch the posts in unread items so that I can read all posts in a single window.

So if you follow my blog , you don't have to come to my site whenever I post new one. It will get updated in your reader view.

You can import subscribed blogs from your friends also.Say if you want to follow blogs that whatever am following, you can easily import my blogs list from me.For that I have to export my blog list from reader settings.It will give you the OPML file which you can easily import it in your reader settings.


If you need my blogs list just ping me to amicable.ad@gmail.com.I will send you OPML file '.