Friday 30 November 2012

Hosting Rails app : uhurucloud.com

I'm great fan of Heroku : ease with which it let you deploy your app.
In a quick minute you can set your app up and running. There are other many app providers out there and recently i come across another one: uhurucloud.com. 
It let you deploy your app without the need of adding/committing in any git repo.(git add .. git commit -m..) .
It's very easy to deploy RoR app on uhurucloud in just two step: 1) Make your app. 2) run vmcu PUSH command.

 I am working on my online resume. And i need space to upload my project list.  Currently I'm in a mid of development and not yet completed it but the work so far can be seen here.

Here is a quick step by step tutorial on deploying your app on uhurucloud.com without using any extra gem(capistrano) or pulling/pushing any git repository.


1) Install uruhu gem :  vmcu


2) Select target service

3) login into vmcu
             3.1) Get one time token
                                   Go to your uruhu cloud dashboard click the icon next to your instance name.
                                 copy the token so generated upon the screen.

3.2) Now login with your username and your one time token you just copied.




 4) Set cloud team which is nothing but the instance you created on uhuru.
I made with name "sahilsk" .


Push your app into the cloud

5) Change directory to your app root folder
    cd  /path/to/rails/app/root

5) vcmu push
You are now all ready to push your app into the cloud.
uhuru will automatically detect your application language.
It'll ask you few basic questions.

$ vmcu push
Would you like to deploy from the current directory? [Yn]: y
Application Name: portfolio
Detected a Rails Application, is this correct? [Yn]: y
Application Deployed URL [portfolio.uhurucloud.com]: sahilsk.uhurucloud.com
Memory reservation (128M, 256M, 512M, 1G, 2G) [256M]: 512M
How many instances? [1]:
Create services to bind to 'portfolio'? [yN]: y
1: mongodb
2: mssql
3: mysql
4: postgresql
5: rabbitmq
6: redis
7: uhurufs
What kind of service?: 3
Specify the name of the service [mysql-dcf11]:
Create another? [yN]: n
Would you like to save this configuration? [yN]: y
Manifest written to manifest.yml.
Creating Application: OK
Creating Service [mysql-dcf11]: OK
Binding Service [mysql-dcf11]: OK
Uploading Application:
  Checking for available resources: OK
  Processing resources: OK
  Packing application: OK
  Uploading (1M): OK
Push Status: OK

Staging Application 'portfolio': OK

Starting Application 'portfolio': OK

You are not all set.

open the application deployed url:  sahilsk.uhurucloud.com
YOu can see your application up and running.


Hurdles:
  I was using rails app 3.x. So, many a times after push operation my app was getting syntax error.
Problem was the use of new hash-key pair style inside session_store.rb and wrap_parameters.rb.
key:  value
I changed them to old school style.
:key=> value

then i re-run vmcu push. It will not ask you to fill the parameteres again if you had choosen to remember the configuration during the first push command .
After that everything works as expected.


References:
command line deployement : 
 http://support.uhurusoftware.com/entries/21454287-deploying-and-managing-apps-with-command-line

Getting one time token: 
http://support.uhurusoftware.com/entries/21595322-the-uhuru-appcloud-web-manager-getting-a-token

Monday 26 November 2012

Store ID's in has_many or habtm associated tables

In has_many or habtm association we sometime need to store array of id's.
So, this is how we do it.

table : Projects,  :Categories
Model: Project, Category

html form

    = f.select :category_ids, Category.all.collect{|p| [p.name, p.id]},{:include_blank => false, :prompt=>"select catgory" }, :multiple=>true



And in the controller maintain your normal flow.


def create
    if params
      @project = Project.create( params[:project])
      #@project.categories << params[:project][:category_ids]
      if @project.save
        flash[:success] = "Project created successfully"
        redirect_to :action=>"list"
        return
      else
        @project.screenshot = nil
        params[:project][:screenshot] = nil
        flash[:error] = @project.errors
      end
    end
    render :action=>"new"
end







Monday 22 October 2012

Ruby Enterprise Installation


Get link to latest REE
At the time of writing i had  ruby-enterprise-1.8.7-2012.02.

Get tar file link
http://rubyenterpriseedition.googlecode.com/files/ruby-enterprise-1.8.7-2012.02.tar.gz

$wget http://rubyenterpriseedition.googlecode.com/files/ruby-enterprise-1.8.7-2012.02.tar.gz

tar -xzf ruby-enterprise-1.8.7-2012.02.tar.gz

Install

cd ruby-enterprise-1.8.7-2012.02

Install
sudo ./installer

If you come across any error,then make following changes


->Open source/distro/google-perftools-1.7/src/tcmalloc.cc in your favorite editor and g to line 1672.
You will see this:
        void *(*__memalign_hook)(size_t, size_t, const void *) = MemalignOverride;
However this should look like this:
        void *(* volatile __memalign_hook)(size_t, size_t, const void *) = MemalignOverride;
Save and close the file.

sudo ./installer


Add to your path variable

Ruby Enterprise Edition installation, modification of PATH variable for all users:
echo "export PATH=\$PATH:/opt/ruby-enterprise-1.8.7-2012.02/bin" > /etc/profile.d/ruby-ee-path.sh

export PATH=$PATH:/opt/ruby-enterprise-1.8.7-2012.02/bin



Install openssl


  sudo apt-get install build-essential bison openssl libreadline6 libreadline6-dev curl git-core zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-0 libsqlite3-dev sqlite3 libxml2-dev libxslt-dev autoconf libc6-dev ncurses-dev
sudo apt-get install libssl0.9.8



Install Rails

gem install rails -v 3.0

Sunday 23 September 2012

Rails sql query cheat sheet

Model name :  XXX, :pluralize=>xxxS

Find query:

XXX.find(1)  # => select * from XXX where id=1
     NOTE: it raise exception when no record found


 Better use this one:
XXX.find_by_id(1) #=> Works perfectly without raising andy exception

WHERE clause
XXX.find(:all , :conditions=>['id =?', 1] )

ORDER
XXX.find(:all, :order => "date")

WHERE clause many conditions
XXX.find(:all, :conditions => ['XXX_ID not in (?)', (@xxxS.empty? ? '' : @xxxS.map(&:id))])
Topic.where( 'forum_id not in (?)', (@forums.empty? ? '' : @forums.map(&:id)) ).all


find(:all, :select => "name").map(&:name)  # find all records, then map name attributes to an array


SUM
Grouping with multiple columns cannot be supported by rails. You have to use a regular find all:
budgets = Budgets.find(:all, 
                       :select => "emptype_id, calendar_id, sum(budgets.actual_head) AS sum_actual_head", 
                       :group => "emptype_id, calendar_id")

Budgets.sum(:actual_head ,:group=>["emptype_id"," calendar_id"] )
'NOT IN' operations

Topic.all - @forums.map(&:id)

Join Operations

Topic.all(:joins => "left join forums on (forums.id = topics.forum_id and some_condition)", :conditions => "forums.id is null")


Deletion of  HABTM intersection table
  Menus.items.delete( Item.find_by_id(1) );                                      # ! IMPORTANT

Nested Select Statements

@answers = Answer.select([:id, :content, :points])
.where(question_id: @questions.pluck(:id))


This is the same as:


         SELECT id, content, points 
FROM answers 
WHERE question_id in (<question_ids array>)




 
References:
http://ar.rubyonrails.org/classes/ActiveRecord/Calculations/ClassMethods.html

Saturday 22 September 2012

HABTM relation: Adding Record


class Menu < ActiveRecord::Base
...
  has_and_belongs_to_many :items, :join_table=>"menus_items"
  ...
end

Update image using paperclip: Rails way

Paperclip is a nice and widely preferred way of uploading datasets into your rails application.

Installation of paperclip:

Add "gem "paperclip"  in your gem file
run 'bundle install'
Restart the server
----------

Saturday 28 July 2012

Troubleshooting Heroku/Git deployment

Trouble  shooting Heorku/Git deployment


Problem1:  Permission denied (publickey).
git push heroku master
Permission denied (publickey).
fatal: The remote end hung up unexpectedly

Solution:
  Add public key to heroku:
heroku keys:add ~/.ssh/id_rsa.pub

Problem 2: error:src refspec master does not match any.
$ git push heroku master
error: src refspec master does not match any.
error: failed to push some refs to 'git@heroku.com:bliss.git'

Solution:
 You never committed. So, first commit and proceed.
$~ git commit -m 'initial commit'
$~ git push origin master

Wednesday 25 July 2012

How to move an item to an empty list using jquery?

If you understand the question then you might know it's related to jquery-ui sortable function which though successfully helped to move items between list but fail to add item in a list when it gets empty.

It was earlier reported as a bug and solution to this one was to add width and height to your list.
http://bugs.jqueryui.com/ticket/2940




<ul id="sortable1" class="connectedSortable">
 <li class="ui-state-default">Item 1</li>
 <li class="ui-state-default">Item 2</li>
 <li class="ui-state-default">Item 3</li>
 <li class="ui-state-default">Item 4</li>
 <li class="ui-state-default">Item 5</li>
</ul>

<ul id="sortable2" class="connectedSortable">
 <li class="ui-state-highlight">Item 1</li>
 <li class="ui-state-highlight">Item 2</li>
 <li class="ui-state-highlight">Item 3</li>
 <li class="ui-state-highlight">Item 4</li>
 <li class="ui-state-highlight">Item 5</li>
</ul>



First task: Make them sortable among them.

 <script>
 $(function() {
  $( "#sortable1, #sortable2" ).sortable({
   connectWith: ".connectedSortable"
  }).disableSelection();
 });
 </script>



Second task: Add element to empty list


bingooo .You can't.

Solution:

Add height to your UL /OL list. I gave it by adding padding to it.

.connectedSortable{
   padding-bottom: 10px;
}

Friday 20 July 2012

Errors while compiling libssh2 and their remedies


While building libssh2 you may come across zlib.h or unistd.h related error.  Solution to each problem is given below.


1) ...\comp.c(40) : fatal error C1083: Cannot open include file: 'zlib.h': No such file or directory

Download zlib developer files fromt this link: http://gnuwin32.sourceforge.net/packages/zlib.htm

Download link: http://gnuwin32.sourceforge.net/downlinks/zlib-lib-zip.php



2)..\zconf.h(289) : fatal error C1083: Cannot open include file: 'unistd.h': No such file or directory


zlib under windows requires libgw32c

To compile with zlib on windows libgw32c is required http://gnuwin32.sourceforge.net/packages/libgw32c.htm to prevent:
c:\program files\gnuwin32\include\zconf.h(289) : fatal error C1083: Cannot open include file: 'unistd.h': No such file or directory

Download link: http://gnuwin32.sourceforge.net/downlinks/libgw32c-lib-zip.php


Friday 23 March 2012

CakePHP: Database Associations


Table Associations


CREATE TABLE `posts` (
`id` int(11) unsigned NOT NULL auto_increment,
`name` varchar(255) default NULL,
`date` datetime default NULL,
`content` text,
`user_id` int(11) default NULL,
PRIMARY KEY (`id`)
);

CREATE TABLE `comments` (
`id` int(11) unsigned NOT NULL auto_increment,
`name` varchar(100) default NULL,
`content` text,
`post_id` int(11) default NULL,
PRIMARY KEY (`id`)
);

Git: Most oftenly used commands


Global setup:

 Set up git
  git config --global user.name "sonu"
  git config --global user.email sonukr666@gmail.com

Next steps:

  mkdir dfd
  cd dfd
  git init
  touch README
  git add README
  git commit -m 'first commit'
  git remote add origin git@github.com:sahilsonu/dfd.git
  git push -u origin master

CakePhp : Naming Conventions

Naming Conventions:


Naming Controllers:

Each controller name must match a database table name.
If you decide to create controllers with names other than tables of the database, you should actually not create a controller but use a component instead .

The names of database tables as well as controllers are lowercase and in plural form.
eg.  Table name: orders, special_orders

Saturday 18 February 2012

RoR : Migration

Little on ruby On rails Migration


Migrations: If you want to make any changes in the database, then migration come into picture.

How to create migration:
>>rails generate migration migration_name

Tuesday 14 February 2012

How to install Git on window? How to install Git on window?

How to install Git on window?


You can install git on window platform either through cygwin or by downloading msysGit. I've chosen the later one: msysGit



WinCygwinhttp://www.cygwin.com/setup.exe
msysGithttp://code.google.com/p/msysgit/downloads/list

So, go to msysGit and download the window installer or zip file, whatever that suits you.
Extract/install it.
 Once done, add path to git`s bin directory in window Environment PATH variable.

Saturday 11 February 2012

Errors While RoRing


/*****************************ISSUE: 1****************************************/
C:\Ruby192\bin>gem install kgio

Temporarily enhancing PATH to include DevKit...

Building native extensions.  This could take a while...

ERROR:  Error installing kgio:
        ERROR: Failed to build gem native extension.

C:/Ruby192/bin/ruby.exe extconf.rb
checking for poll() in poll.h... no
checking for getaddrinfo() in sys/types.h,sys/socket.h,netdb.h... no
getaddrinfo required
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of
necessary libraries and/or headers.  Check the mkmf.log file for more
details.  You may need configuration options.

Friday 13 January 2012

Conversion from wchar_t to char * and vice versa

 Conversion from wchar_t to char * and vice versa



Converts a sequence of multibyte characters to a corresponding sequence of wide characters.
size_t mbstowcs(
   wchar_t *wcstr,
   const char *mbstr,
   size_t count 
)

Thursday 12 January 2012

Wednesday 11 January 2012

some useful CURL's command line arguments

Some useful CURL's command line arguments

Curl follow location : use "-L" option
   i.e If page redirects, curl should redirect to that page as well or to follow the location
    curl -L -b google.com

Curl add proxy 
    curl -x 172.28.1.253:8080 ftp://ftp.leachsite.com/README

Curl user agent

WAIT() function in c/c++


WAIT() function in c/c++
#include <stdio.h>
#include <time.h>

void wait ( int seconds )
{
  clock_t endwait;
  endwait = clock () + seconds * CLOCKS_PER_SEC ;
  while (clock() < endwait) {}
}

Wednesday 4 January 2012

libtidy : convert html to xml

LIBTIDY: Tidy up your html code


Out of various uses of libtidy, this post contain one simple use of libtidy.
It convert your html page code, parse it , tidy it  and finally produce an xml doc ready to be fed to your xml parser like libxml.

For that we either provide command line options to the tidy or we can write down all the command line option in a single file so that we only need to pass only one command line argument and that is you guess it right, it's config file path. :D