Tuesday, August 26, 2014

Useful rails methods

Links

<% link_to 'Name', name_path(:param=> 'variable'), :class => 'css' %>

Redirection

In Controller -> redirect_to name_path
In Views ->
<% if developer_signed_in? %>
    <script type="text/javascript">
        window.location.href="/dashboard"  // put your correct path in a string here
    </script>
<%else%>


Killing process in Linux

ps aux | grep (process name)
kill processID

Make Devise Authenticable to controller classes

class YourController < ApplicationController
  before_action :set_unlock_code, only: [:show, :edit, :update, :destroy]

  #Only signed in user can do the following (Devise)
  before_filter :authenticate_developer!
end

Parsing Form tag with parameters

Unlike form_for tag, this tag pass the values with params

In the View
    <%= form_tag generate_codes_path, :class => 'form-inline' do %>
        <div class="form-group">        <%= number_field_tag 'unlock_code[strAppId]', nil, :placeholder => 'App ID' %>              </div>
        <div class="form-group">        <%= number_field_tag 'unlock_code[batchNo]', nil, :placeholder => 'Batch No' %>             </div>
        <div class="form-group">        <%= text_field_tag 'unlock_code[strStatus]', nil, :placeholder => 'Status' %>               </div>
        <div class="form-group">        <%= number_field_tag 'unlock_code[priceUniversal]', nil, :placeholder => 'Price in USD' %>  </div>
        <div class="form-group">        <%= number_field_tag 'unlock_code[priceMMK]', nil, :placeholder => 'Price in MMK' %>        </div>
        <div class="form-group">        <%= number_field_tag 'unlock_code[num]', nil, :placeholder => 'Number of codes' %>          </div>

        <%=  submit_tag 'Generate', :class => "btn btn-primary md-trigger" %>
    <% end %>

In the controller tag
    strAppId = params[:strAppId]
    batchNo = params[:batchNo]
    strStatus = params[:strStatus]
    priceUniversal = params[:priceUniversal]
    priceMMK = params[:priceMMK]
    num = params[:num]

Field Parameters

<%= number_field_tag 'appID', '-1', :placeholder => 'App ID', :required => true , :disabled => true%>



Saturday, August 23, 2014

Devise Configurations

Some setup you must do manually if you haven't yet:

  1. Ensure you have defined default url options in your environments files. Here is an example of default_url_options appropriate for a development environment in config/environments/development.rb:

       config.action_mailer.default_url_options = { host: 'localhost', port: 3000 }

     In production, :host should be set to the actual host of your application.

  2. Ensure you have defined root_url to *something* in your config/routes.rb.
     For example:

       root to: "home#index"

  3. Ensure you have flash messages in app/views/layouts/application.html.erb.
     For example:

       <p class="notice"><%= notice %></p>
       <p class="alert"><%= alert %></p>

  4. If you are deploying on Heroku with Rails 3.2 only, you may want to set:

       config.assets.initialize_on_precompile = false

     On config/application.rb forcing your application to not access the DB
     or load models when precompiling your assets.

  5. You can copy Devise views (for customization) to your app by running:

       rails g devise:views

Other Nice Ruby On Rails Tutorial Links

Friday, August 22, 2014

Install Ruby Stack on windows

As ruby on rails can also be deployed in windows server, you might need to download and install several components that requires for ruby on rails development.

After I did some research on internet and did manual installation of all the required software and components for windows development, I found it really hard just to install all these software packs.

Bitnami has so many use full one-click deployment stack that's so useful for beginner like us to develop and deply Ruby on rails application with one click.

Run the following command to trace the installation errors which might happens sometimes.
"K:\Software\For Windows\Ruby On Rails\bitnami-rubystack-2.0.0-18-windows-installer.exe" --debugtrace C:\output.log

You can check out more about bitnami stack from here.
https://bitnami.com/
https://bitnami.com/stacks
https://bitnami.com/stack/ruby

You can just download the windows stack and click install to install the whole stack that're required for developing ruby on rails application app on windows.

Make sure you disable your AntiVirus, Windows defender and firewall with full administer access to avoid the disruption with the installation.

If your port 80 is already binded from another application, just use 8080 for web port and 442 as SSL port. As this will be just used for development only, these port really doesn't matter.

For Ruby development IDE, Ruby Mine works great with full syntax recognition and intellisense.

Steps by steps guilde to new rails app development


Creating a new rails app

rails new appfolder/appname

Installing the default gems

bundle install

Note : If you're developing Ruby on rails on Windows for the first time. you need the following command as libv8 usually doesn't support Windows.


gem install libv8 -v '3.11.8.17' -- --with-system-v8


Installing JQuery

add gem'jquery-rails' to your gem file and make bundle install
don't need to do rails g jquery:install from rails 3 as assets pipeline already take care of it.

Using Devise to generate User

add gem 'devise' to your gem file.

rails generate devise:install
rails generate devise User
rake db:migrate
rake routes

List of Devise default paths


new_user_session GET    /users/sign_in(.:format)       devise/sessions#new
user_session POST   /users/sign_in(.:format)       devise/sessions#create
destroy_user_session DELETE /users/sign_out(.:format)      devise/sessions#destroy
user_password POST   /users/password(.:format)      devise/passwords#create
new_user_password GET    /users/password/new(.:format)  devise/passwords#new
edit_user_password GET    /users/password/edit(.:format) devise/passwords#edit
                         PUT    /users/password(.:format)      devise/passwords#update
cancel_user_registration GET    /users/cancel(.:format)        devise/registrations#cancel
user_registration POST   /users(.:format)               devise/registrations#create
new_user_registration GET    /users/sign_up(.:format)       devise/registrations#new
edit_user_registration GET    /users/edit(.:format)          devise/registrations#edit
                         PUT    /users(.:format)               devise/registrations#update
                         DELETE /users(.:format)               devise/registrations#destroy


If you want to customise the views for the devise, you could call the following rails command.

rails generate devise:views

Code scaffolding with rails

rails g scaffold Food user_id:integer title:string description:string categor
ies:string icon_url:string screenshot_url_01:string

Generate only controller class

rails g controller StaticPages

Installing Redis and Sinatra for API development

gem install redis
gem install sinatra
gem install sinatra-params-validator


Installing puma server ( not working for now)

gem install puma 
or for Windows, you have to pass with the path to openssl 

http://packages.openknapsack.org/openssl/openssl-1.0.0k-x64-windows.tar.lzma

  1. install DevKit, e.g. in c:\devkit
  2. unpack the OpenSSL Package, e.g. in c:\openssl (use 7Zip or PeaZip)
  3. You need to copy the ddls from the bin directory (libeay32.dll andssleay32.dll) to your ruby/bin directory.
  4. open a windows console
  5. initialize the DevKit build environment
    c:\devkit\devkitvars.bat
  6. Now it’s possible to install the puma gem with the OpenSSL packages
    gem install puma -- --with-opt-dir=c:\openssl
C:\>mkdir C:\Knapsack\x64-windows
C:\>cd C:\Knapsack\x64-windows
C:\Knapsack\x64-windows>bsdtar --lzma -xf openssl-1.0.0k-x64-windows.tar.lzma
C:\>gem install puma --platform=ruby -- --with-opt-dir=C:/Knapsack/x64-windowsgem install puma --platform=ruby -- --with-opt-dir=C:/Knapsack/x64-windows

Bitnami RubyStack configuration in Digital Ocean.

I am using Digital Ocean for the stack. Digital Ocean is the cheapest cloud solution provider compare to Amazon, Rackspace and other providers.

Create an account with Digital Ocean and create a new droplet in the dashboard from Digital Ocean.

Once you've created the new droplet, you will be given the default with the username "root".
Login to your server with the default password and type passwd and you will be asked for new Unix password .


Installing Bitnami Stack

First download the linux stack by using the following command in the root directory.

wget http://downloads.bitnami.org/files/stacks/rubystack/1.9.3-5/bitnami-rubystack-1.9.3-5-linux-installer.run


Give the application to runnable permission 

chmod 755 bitnami-rubystack-1.9.3-5-linux-installer.run


Install the downloaded stack from ssh

After you've run the downloaded file with shell, you will be asked for all the configurations to be installed with the stack. Carefully read the steps and continue installation.
./bitnami-rubystack-1.9.3-5-linux-installer.run

After the installation is done, Choose Yes to the option(Open Bitnami Stack in Browser) and you are ready to see your stack by providing the ip address of your Digital Ocean droplet.


Installing Postgresql Server

If you're deploying your web app, you might have to use Postgresql server for database as sqlite might be insufficient solution in long terms.

Go to your server root if you're not there yet by typing cd ~

Bitnami also provide the postgresql module and you can download by typing


sudo apt-get update
sudo apt-get install postgresql postgresql-contrib
or Direct download and run from
wget http://downloads.bitnami.org/files/stacks/postgresql/5.4.11-1/bitnami-postgresql-5.4.11-1-module-linux-installer.run


Give the application to runnable permission and run with shell

chmod 755 bitnami-postgresql-5.4.11-1-module-linux-installer.run
./bitnami-postgresql-5.4.11-1-module-linux-installer.run

You will then be asked to choose the folder. Type the folder that you installed Bitnami Stack into. Default is "/opt/rubystack-1.9.3-5/"


Running the Bitnami Ruby Console

Everytime you're calling the ruby and rails command, you will need to run the rubyconsole inside rubystack.

Now go to cd /opt/rubystack-1.9.3-5 and run the rubyconsole.
./rubyconsole


Installing Vim (GUI Version)

sudo apt-get install vim-gnome
sudo apt-get install vim

Creating a shell script for ruby console

Let's make a shell script as you might have to do the previous steps of running rubyconsole everytime you log into the account
go back to your root folder cd ~
create a new shell script file by typing vim run_rc.sh in root folder.
Press "I" for insert mode and type the following 

echo "run ruby console..."
cd /opt/rubystack-1.9.3-5/
./rubyconsole

After than Press Shift + ; and write "wq" for write the file and quit from vim.
Give the file permission to runnable by typing
chmod 755 run_rc.sh

Now everytime you login to your console, you just have to type
./run_rc.sh which will redirect to your ruby stack installation folder.


Configuring VHost file in Apache

Now you can go to the following directory.
/opt/rubystack-1.9.3-5/apache2/conf/extra

Open the vim httpd-vhosts.conf file and apply the following VHost configuration as you need.

#
# Use name-based virtual hosting.
#
NameVirtualHost *:80

<VirtualHost *:80>
      ServerName yourdomain.com
      ServerAlias www.youdomain.com
      DocumentRoot  /opt/rubystack-1.9.3-5/apps/rails_app_folder/public       
      <Directory /opt/rubystack-1.9.3-5/apps/rails_app_folder/public>         
         AllowOverride all
         Options -MultiViews
      </Directory>
</VirtualHost>

#API Server
<VirtualHost *:80>
      ServerName api.youdomain.com
      ProxyPass / http://localhost:4567/
      ProxyPassReverse / http://localhost:4567/
</VirtualHost>

<Directory /> 
#Options FollowSymLinks 
Options Indexes FollowSymLinks Includes ExecCGI 
AllowOverride All 
Order deny,allow 
Allow from all 
</Directory>

Setting up DNS and name servers

If you're using GoDaddy, make sure you park your domain first if you're using nameservers from your previous hosting services. Go to the domain management dashboard. (All Products->Domain->Domain Management)
Click on your domain to go to the DNS manager. Click Edit Zone and remove the existing Points to and A Records in Host section and add new record which points to your server IP address. and click submit. It might take up to 2 hours so don't worry about it if the DNS is not changed instantly.


Generating SSH Keys

Type the following command in console
mkdir ~/.ssh
chmod 700 ~/.ssh
ssh-keygen -t rsa\ or ssh-keyben

Most Ubuntu OS already has .ssh folder and you can just start from step 2.

You will be prompted for a location to save the keys, and a passphrase for the keys. This passphrase will protect your private key while it's stored on the hard drive and be required to use the keys every time you need to login to a key-based system.


Installing Thin Server

Update apt list first
sudo apt-get update

Before installing the thin server, g++ needs to be downloaded and installed.
sudo apt-get install g++

you also have to make sure the build environment essential is already installed in your system. If not try installing the build essential
sudo apt-get install build-essential

Now you can install thin server 
gem install thin

Installing Nodejs 

You will need to install nodejs if you are using javascript and jQuery in your ruby on rails app
sudo apt-get install nodejs (Don't do this)


mkdir ~/node-latest-install
cd ~/node-latest-install
curl http://nodejs.org/dist/node-latest.tar.gz | tar xz --strip-components=1
./configure --prefix=~/local
make install
curl http://npmjs.org/install.sh | sh


Installing Coffee script

If you're using coffee scripts in your rails app, you will have to install coffee script as it's not installed by default.


npm install -g coffee-script

Installing Redis Cache Server

Normally : Redis server is already included with Bitnami Stack so check 
redis-cli ping first and if you receive pong result, you can skip this step.

sudo apt-get install redis-server

you can check the redis-server working by calling
redis-cli ping and you will receive Pong result
you can just type redis-cli to use all the redis command after that

wget http://redis.googlecode.com/files/redis-2.4.16.tar.gz
tar xzf redis-2.4.16.tar.gz
cd redis-2.4.16
make
make test
sudo make install
cd utils
sudo ./install_server.sh
sudo service redis_6379 start 
sudo service redis_6379 stop

Use the following command to start redis server at boot
sudo update-rc.d redis_6379 defaults

Restarting the apache server

After you've done all the configurations including vHosts setting, you will have to restart the apache service. Go to your rubystack installation in my case /opt/rubystack-1.9.3-5/

and run ./ctlscript.sh restart


FTP server permissions

create a new user

root@Server:/etc# sudo chmod 777 passwd

root@Server:/etc# vim passwd



Point to /opt/rubystack1.9.3-5/apache2/htdocs


Changing Permission of phpPGAdmin

go to /opt/bitnami/apache2/apps/phppgadmin/conf/phppgadmin.conf
and change "Allow from 127.0.0.1" to "Allow from all"
and then restart the apache server

after that, go to http://your_ip_address/phppgadmin/ to access postgresql admin panel from web browser.

Changing Postgres default password

Default username is postgres and password is what you defined earlier


$ psql -U postgres
postgres=# alter user postgres with password 'YOUR_NEW_PASSWORD';
postgresl=# \q



Creating new database in Postgresql server

cd ~ to go back to the root
createdb database_name to create a new database and you will be prompted for a password and type the password for the superuser.