1200.2345.round
o/p: 1200
1200.2345.round_with_precision(2)
o/p: 1200.23
Currency format in rails
number_to_currency is the helper method provided by rails action view helpers. The options were
:precision - Sets the level of precision (defaults to 2).
:unit - Sets the denomination of the currency (defaults to "$").
:separator - Sets the separator between the units (defaults to ".").
:delimiter - Sets the thousands delimiter (defaults to ",").
:format - Sets the format of the output string (defaults to "%u%n").
Using this method, we could write something like this:
<%=h number_to_currency @transaction.value, :unit => 'Rs', :separator => ",", :delimiter => "." %>
This would work fine, but here we breaking the DRY (Don't Repeat Yourself) rule, because I would need to set the same parameters in every place I was displaying currency values in my entire site. A better solution would be to have a helper method which I could use in every where in my application. So I came up with the solution below, which consists in writing my own helper method in app/helpers/application_helper.rb:
module ApplicationHelper
def real_currency(number)
number_to_currency(number,:delimiter => ".", :unit => "Rs ",:separator => ",")
end
end
Now, I can use <%=h real_currency @transaction.value %> every where in my templates.
Showing posts with label Ruby on Rails. Show all posts
Showing posts with label Ruby on Rails. Show all posts
Thursday, August 12, 2010
Tuesday, August 10, 2010
Very Usefull Ruby on Rails URLs
10 Reasons to learn ruby
http://www.h3rald.com/articles/10-reasons-to-learn-ruby/
Awesome ruby tidbits
http://www.rubyinside.com/interesting-ruby-tidbits-that-dont-warrant-separate-posts-1-600.html
Web based deployment using webistrano
http://blog.innerewut.de/webistrano/
http://www.h3rald.com/articles/10-reasons-to-learn-ruby/
Awesome ruby tidbits
http://www.rubyinside.com/interesting-ruby-tidbits-that-dont-warrant-separate-posts-1-600.html
Web based deployment using webistrano
http://blog.innerewut.de/webistrano/
Monday, July 26, 2010
Important URLs for RoR Developement
Official Website
http://rubyonrails.org/
Great Start
http://www.akitaonrails.com/2007/12/12/rolling-with-rails-2-0-the-first-full-tutorial
Examples
http://www.tutorialspoint.com/ruby-on-rails/rails-examples.htm
Sample applications with basic features like authentication and admin features
http://www.railsinside.com/elsewhere/100-7-barebones-rails-apps-to-kick-start-your-development-process.html
Many to Many Relationship with Multi select control in rails
http://blog.coryfoy.com/2008/02/multiselect-control-in-rails-with-a-many-to-many-relationship/
Develop Facebook application
http://www.liverail.net/articles/2007/6/29/tutorial-on-developing-a-facebook-platform-application-with-ruby-on-rails
http://rubyonrails.org/
Great Start
http://www.akitaonrails.com/2007/12/12/rolling-with-rails-2-0-the-first-full-tutorial
Examples
http://www.tutorialspoint.com/ruby-on-rails/rails-examples.htm
Sample applications with basic features like authentication and admin features
http://www.railsinside.com/elsewhere/100-7-barebones-rails-apps-to-kick-start-your-development-process.html
Many to Many Relationship with Multi select control in rails
http://blog.coryfoy.com/2008/02/multiselect-control-in-rails-with-a-many-to-many-relationship/
Develop Facebook application
http://www.liverail.net/articles/2007/6/29/tutorial-on-developing-a-facebook-platform-application-with-ruby-on-rails
Friday, July 23, 2010
Restart live server for your rails application
When you change any modifications in models or configuration files, then changes will not apply in server some times, in that situation you need to restart the server by connecting your hosting server through telnet. Follow the below process
Login through telnet and enter into the application root path
Ex:# ssh root@example.com
Goto application path
Ex: cd /var/www/example.com
Then run the following commands
# mongrel_rails stop
# mongrel_rails start -d
Login through telnet and enter into the application root path
Ex:# ssh root@example.com
Goto application path
Ex: cd /var/www/example.com
Then run the following commands
# mongrel_rails stop
# mongrel_rails start -d
Tuesday, July 20, 2010
(QA) Testing, Staging and Production environments are now available with Heroku
Hi There,
Deploying application in multiple environements is a better approach for a successfull appliation. This is the default behaviour of the rails application to maintain deployment in development, testing and production environments. Development and testing versions are live on developer's local system and production environement lives on actual server.
Now heroku offers us to maintain the application with these three evnironments in live server withing heroku so that clients and your colleagues can provide feedback and suggestions on your application before pushing them to production.
Ex: If you want to deploy an application called "myapp" in Heroku. First create the production,staging and testing(QA) versions of the application, should use --remote option to override the defaults for the git repository names.
$ heroku create myapp-production --remote production
$ heroku create myapp-staging --remote staging
$ heroku create myapp-qa --remote qa
Now, if you want to deploy code to a particular environemt, do so by specifying the appropriate option
Ex:
$ git push staging master
and if you need to run db migrations use below
$ heroku rake db:migrate --remote staging
Finally, If you probably want to periodically copy your production data into your staging environment:
$ heroku db:pull --remote production
$ heroku db:push --remote staging
Now, when you want to deploy code to a particular environment, do so by specifying the appropriate remote:
$ git push staging master
And if you need to run migrations:
$ heroku rake db:migrate --remote staging
Finally, you will probably want to periodically copy your production data into your staging environment:
$ heroku db:pull --remote production
$ heroku db:push --remote staging
Note: Keep in mind that any environment variables you create or add-ons you add must be duplicated across environments for a consistent experience. For example, if you begin using memcache on your staging app, be sure to install it on your production app before you deploy your new code.
For more details
http://jqr.github.com/2009/04/25/deploying-multiple-environments-on-heroku.html
http://stackoverflow.com/questions/1279787/staging-instance-on-heroku
Deploying application in multiple environements is a better approach for a successfull appliation. This is the default behaviour of the rails application to maintain deployment in development, testing and production environments. Development and testing versions are live on developer's local system and production environement lives on actual server.
Now heroku offers us to maintain the application with these three evnironments in live server withing heroku so that clients and your colleagues can provide feedback and suggestions on your application before pushing them to production.
Ex: If you want to deploy an application called "myapp" in Heroku. First create the production,staging and testing(QA) versions of the application, should use --remote option to override the defaults for the git repository names.
$ heroku create myapp-production --remote production
$ heroku create myapp-staging --remote staging
$ heroku create myapp-qa --remote qa
Now, if you want to deploy code to a particular environemt, do so by specifying the appropriate option
Ex:
$ git push staging master
and if you need to run db migrations use below
$ heroku rake db:migrate --remote staging
Finally, If you probably want to periodically copy your production data into your staging environment:
$ heroku db:pull --remote production
$ heroku db:push --remote staging
Now, when you want to deploy code to a particular environment, do so by specifying the appropriate remote:
$ git push staging master
And if you need to run migrations:
$ heroku rake db:migrate --remote staging
Finally, you will probably want to periodically copy your production data into your staging environment:
$ heroku db:pull --remote production
$ heroku db:push --remote staging
Note: Keep in mind that any environment variables you create or add-ons you add must be duplicated across environments for a consistent experience. For example, if you begin using memcache on your staging app, be sure to install it on your production app before you deploy your new code.
For more details
http://jqr.github.com/2009/04/25/deploying-multiple-environments-on-heroku.html
http://stackoverflow.com/questions/1279787/staging-instance-on-heroku
Wednesday, July 14, 2010
Build IPhone native appliactions with PHP or Ruby code
If you wanna develop IPhone native applications and don't have the time to learn completely new language i.e Objective - C, Now it is possible for the PHP and Ruby developers. By using one third party service you can write code in either PHP or Ruby and build native IPhone application also can use Html and CSS for UI Design.
You can download the source from here : http://www.appcelerator.com/
Other available tools to develop Iphone and wap applications.
You can download the source from here : http://www.appcelerator.com/
Other available tools to develop Iphone and wap applications.
Monday, May 24, 2010
About Rails Framework
Rails is a web-application and persistence framework that includes everything
needed to create database-backed web-applications according to the
Model-View-Control pattern of separation. This pattern splits the view (also
called the presentation) into "dumb" templates that are primarily responsible
for inserting pre-built data in between HTML tags. The model contains the
"smart" domain objects (such as Account, Product, Person, Post) that holds all
the business logic and knows how to persist themselves to a database. The
controller handles the incoming requests (such as Save New Account, Update
Product, Show Post) by manipulating the model and directing data to the view.
In Rails, the model is handled by what's called an object-relational mapping
layer entitled Active Record. This layer allows you to present the data from
database rows as objects and embellish these data objects with business logic
methods. You can read more about Active Record in
link:files/vendor/rails/activerecord/README.html.
The controller and view are handled by the Action Pack, which handles both
layers by its two parts: Action View and Action Controller. These two layers
are bundled in a single package due to their heavy interdependence. This is
unlike the relationship between the Active Record and Action Pack that is much
more separate. Each of these packages can be used independently outside of
Rails. You can read more about Action Pack in
link:files/vendor/rails/actionpack/README.html.
== Getting Started
1. At the command prompt, start a new Rails application using the rails command
and your application name. Ex: rails myapp
(If you've downloaded Rails in a complete tgz or zip, this step is already done)
2. Change directory into myapp and start the web server: script/server (run with --help for options)
3. Go to http://localhost:3000/ and get "Welcome aboard: You’re riding the Rails!"
4. Follow the guidelines to start developing your application
== Web Servers
By default, Rails will try to use Mongrel and lighttpd if they are installed, otherwise
Rails will use WEBrick, the webserver that ships with Ruby. When you run script/server,
Rails will check if Mongrel exists, then lighttpd and finally fall back to WEBrick. This ensures
that you can always get up and running quickly.
Mongrel is a Ruby-based webserver with a C component (which requires compilation) that is
suitable for development and deployment of Rails applications. If you have Ruby Gems installed,
getting up and running with mongrel is as easy as: gem install mongrel.
More info at: http://mongrel.rubyforge.org
If Mongrel is not installed, Rails will look for lighttpd. It's considerably faster than
Mongrel and WEBrick and also suited for production use, but requires additional
installation and currently only works well on OS X/Unix (Windows users are encouraged
to start with Mongrel). We recommend version 1.4.11 and higher. You can download it from
http://www.lighttpd.net.
And finally, if neither Mongrel or lighttpd are installed, Rails will use the built-in Ruby
web server, WEBrick. WEBrick is a small Ruby web server suitable for development, but not
for production.
But of course its also possible to run Rails on any platform that supports FCGI.
Apache, LiteSpeed, IIS are just a few. For more information on FCGI,
please visit: http://wiki.rubyonrails.com/rails/pages/FastCGI
== Debugging Rails
Sometimes your application goes wrong. Fortunately there are a lot of tools that
will help you debug it and get it back on the rails.
First area to check is the application log files. Have "tail -f" commands running
on the server.log and development.log. Rails will automatically display debugging
and runtime information to these files. Debugging info will also be shown in the
browser on requests from 127.0.0.1.
You can also log your own messages directly into the log file from your code using
the Ruby logger class from inside your controllers. Example:
class WeblogController < ActionController::Base
def destroy
@weblog = Weblog.find(params[:id])
@weblog.destroy
logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!")
end
end
The result will be a message in your log file along the lines of:
Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1
More information on how to use the logger is at http://www.ruby-doc.org/core/
Also, Ruby documentation can be found at http://www.ruby-lang.org/ including:
* The Learning Ruby (Pickaxe) Book: http://www.ruby-doc.org/docs/ProgrammingRuby/
* Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide)
These two online (and free) books will bring you up to speed on the Ruby language
and also on programming in general.
== Debugger
Debugger support is available through the debugger command when you start your Mongrel or
Webrick server with --debugger. This means that you can break out of execution at any point
in the code, investigate and change the model, AND then resume execution! Example:
class WeblogController < ActionController::Base
def index
@posts = Post.find(:all)
debugger
end
end
So the controller will accept the action, run the first line, then present you
with a IRB prompt in the server window. Here you can do things like:
>> @posts.inspect
=> "[#nil, \"body\"=>nil, \"id\"=>\"1\"}>,
#\"Rails you know!\", \"body\"=>\"Only ten..\", \"id\"=>\"2\"}>]"
>> @posts.first.title = "hello from a debugger"
=> "hello from a debugger"
...and even better is that you can examine how your runtime objects actually work:
>> f = @posts.first
=> #nil, "body"=>nil, "id"=>"1"}>
>> f.
Display all 152 possibilities? (y or n)
Finally, when you're ready to resume execution, you enter "cont"
== Console
You can interact with the domain model by starting the console through script/console.
Here you'll have all parts of the application configured, just like it is when the
application is running. You can inspect domain models, change values, and save to the
database. Starting the script without arguments will launch it in the development environment.
Passing an argument will specify a different environment, like script/console production.
To reload your controllers and models after launching the console run reload!
== Description of Contents
app
Holds all the code that's specific to this particular application.
app/controllers
Holds controllers that should be named like weblogs_controller.rb for
automated URL mapping. All controllers should descend from ApplicationController
which itself descends from ActionController::Base.
app/models
Holds models that should be named like post.rb.
Most models will descend from ActiveRecord::Base.
app/views
Holds the template files for the view that should be named like
weblogs/index.erb for the WeblogsController#index action. All views use eRuby
syntax.
app/views/layouts
Holds the template files for layouts to be used with views. This models the common
header/footer method of wrapping views. In your views, define a layout using the
layout :default and create a file named default.erb. Inside default.erb,
call <% yield %> to render the view using this layout.
app/helpers
Holds view helpers that should be named like weblogs_helper.rb. These are generated
for you automatically when using script/generate for controllers. Helpers can be used to
wrap functionality for your views into methods.
config
Configuration files for the Rails environment, the routing map, the database, and other dependencies.
db
Contains the database schema in schema.rb. db/migrate contains all
the sequence of Migrations for your schema.
doc
This directory is where your application documentation will be stored when generated
using rake doc:app
lib
Application specific libraries. Basically, any kind of custom code that doesn't
belong under controllers, models, or helpers. This directory is in the load path.
public
The directory available for the web server. Contains subdirectories for images, stylesheets,
and javascripts. Also contains the dispatchers and the default HTML files. This should be
set as the DOCUMENT_ROOT of your web server.
script
Helper scripts for automation and generation.
test
Unit and functional tests along with fixtures. When using the script/generate scripts, template
test files will be generated for you and placed in this directory.
vendor
External libraries that the application depends on. Also includes the plugins subdirectory.
This directory is in the load path.
needed to create database-backed web-applications according to the
Model-View-Control pattern of separation. This pattern splits the view (also
called the presentation) into "dumb" templates that are primarily responsible
for inserting pre-built data in between HTML tags. The model contains the
"smart" domain objects (such as Account, Product, Person, Post) that holds all
the business logic and knows how to persist themselves to a database. The
controller handles the incoming requests (such as Save New Account, Update
Product, Show Post) by manipulating the model and directing data to the view.
In Rails, the model is handled by what's called an object-relational mapping
layer entitled Active Record. This layer allows you to present the data from
database rows as objects and embellish these data objects with business logic
methods. You can read more about Active Record in
link:files/vendor/rails/activerecord/README.html.
The controller and view are handled by the Action Pack, which handles both
layers by its two parts: Action View and Action Controller. These two layers
are bundled in a single package due to their heavy interdependence. This is
unlike the relationship between the Active Record and Action Pack that is much
more separate. Each of these packages can be used independently outside of
Rails. You can read more about Action Pack in
link:files/vendor/rails/actionpack/README.html.
== Getting Started
1. At the command prompt, start a new Rails application using the rails command
and your application name. Ex: rails myapp
(If you've downloaded Rails in a complete tgz or zip, this step is already done)
2. Change directory into myapp and start the web server: script/server (run with --help for options)
3. Go to http://localhost:3000/ and get "Welcome aboard: You’re riding the Rails!"
4. Follow the guidelines to start developing your application
== Web Servers
By default, Rails will try to use Mongrel and lighttpd if they are installed, otherwise
Rails will use WEBrick, the webserver that ships with Ruby. When you run script/server,
Rails will check if Mongrel exists, then lighttpd and finally fall back to WEBrick. This ensures
that you can always get up and running quickly.
Mongrel is a Ruby-based webserver with a C component (which requires compilation) that is
suitable for development and deployment of Rails applications. If you have Ruby Gems installed,
getting up and running with mongrel is as easy as: gem install mongrel.
More info at: http://mongrel.rubyforge.org
If Mongrel is not installed, Rails will look for lighttpd. It's considerably faster than
Mongrel and WEBrick and also suited for production use, but requires additional
installation and currently only works well on OS X/Unix (Windows users are encouraged
to start with Mongrel). We recommend version 1.4.11 and higher. You can download it from
http://www.lighttpd.net.
And finally, if neither Mongrel or lighttpd are installed, Rails will use the built-in Ruby
web server, WEBrick. WEBrick is a small Ruby web server suitable for development, but not
for production.
But of course its also possible to run Rails on any platform that supports FCGI.
Apache, LiteSpeed, IIS are just a few. For more information on FCGI,
please visit: http://wiki.rubyonrails.com/rails/pages/FastCGI
== Debugging Rails
Sometimes your application goes wrong. Fortunately there are a lot of tools that
will help you debug it and get it back on the rails.
First area to check is the application log files. Have "tail -f" commands running
on the server.log and development.log. Rails will automatically display debugging
and runtime information to these files. Debugging info will also be shown in the
browser on requests from 127.0.0.1.
You can also log your own messages directly into the log file from your code using
the Ruby logger class from inside your controllers. Example:
class WeblogController < ActionController::Base
def destroy
@weblog = Weblog.find(params[:id])
@weblog.destroy
logger.info("#{Time.now} Destroyed Weblog ID ##{@weblog.id}!")
end
end
The result will be a message in your log file along the lines of:
Mon Oct 08 14:22:29 +1000 2007 Destroyed Weblog ID #1
More information on how to use the logger is at http://www.ruby-doc.org/core/
Also, Ruby documentation can be found at http://www.ruby-lang.org/ including:
* The Learning Ruby (Pickaxe) Book: http://www.ruby-doc.org/docs/ProgrammingRuby/
* Learn to Program: http://pine.fm/LearnToProgram/ (a beginners guide)
These two online (and free) books will bring you up to speed on the Ruby language
and also on programming in general.
== Debugger
Debugger support is available through the debugger command when you start your Mongrel or
Webrick server with --debugger. This means that you can break out of execution at any point
in the code, investigate and change the model, AND then resume execution! Example:
class WeblogController < ActionController::Base
def index
@posts = Post.find(:all)
debugger
end
end
So the controller will accept the action, run the first line, then present you
with a IRB prompt in the server window. Here you can do things like:
>> @posts.inspect
=> "[#
#
>> @posts.first.title = "hello from a debugger"
=> "hello from a debugger"
...and even better is that you can examine how your runtime objects actually work:
>> f = @posts.first
=> #
>> f.
Display all 152 possibilities? (y or n)
Finally, when you're ready to resume execution, you enter "cont"
== Console
You can interact with the domain model by starting the console through script/console.
Here you'll have all parts of the application configured, just like it is when the
application is running. You can inspect domain models, change values, and save to the
database. Starting the script without arguments will launch it in the development environment.
Passing an argument will specify a different environment, like script/console production.
To reload your controllers and models after launching the console run reload!
== Description of Contents
app
Holds all the code that's specific to this particular application.
app/controllers
Holds controllers that should be named like weblogs_controller.rb for
automated URL mapping. All controllers should descend from ApplicationController
which itself descends from ActionController::Base.
app/models
Holds models that should be named like post.rb.
Most models will descend from ActiveRecord::Base.
app/views
Holds the template files for the view that should be named like
weblogs/index.erb for the WeblogsController#index action. All views use eRuby
syntax.
app/views/layouts
Holds the template files for layouts to be used with views. This models the common
header/footer method of wrapping views. In your views, define a layout using the
layout :default and create a file named default.erb. Inside default.erb,
call <% yield %> to render the view using this layout.
app/helpers
Holds view helpers that should be named like weblogs_helper.rb. These are generated
for you automatically when using script/generate for controllers. Helpers can be used to
wrap functionality for your views into methods.
config
Configuration files for the Rails environment, the routing map, the database, and other dependencies.
db
Contains the database schema in schema.rb. db/migrate contains all
the sequence of Migrations for your schema.
doc
This directory is where your application documentation will be stored when generated
using rake doc:app
lib
Application specific libraries. Basically, any kind of custom code that doesn't
belong under controllers, models, or helpers. This directory is in the load path.
public
The directory available for the web server. Contains subdirectories for images, stylesheets,
and javascripts. Also contains the dispatchers and the default HTML files. This should be
set as the DOCUMENT_ROOT of your web server.
script
Helper scripts for automation and generation.
test
Unit and functional tests along with fixtures. When using the script/generate scripts, template
test files will be generated for you and placed in this directory.
vendor
External libraries that the application depends on. Also includes the plugins subdirectory.
This directory is in the load path.
Friday, April 30, 2010
List of heroku commands
Hi,
Below are the list of available list of heroku commands
help # show this usage
version # show the gem version
list # list your apps
create [] # create a new app
keys # show your user's public keys
keys:add [] # add a public key
keys:remove # remove a key by name (user@host)
keys:clear # remove all keys
info # show app info, like web url and
open # open the app in a web browser
rename # rename the app
dynos # scale to qty web processes
workers # scale to qty background processe
sharing:add # add a collaborator
sharing:remove # remove a collaborator
sharing:transfer # transfers the app ownership
domains:add # add a custom domain name
domains:remove # remove a custom domain name
domains:clear # remove all custom domains
ssl:add # add SSL cert to the app
ssl:remove # removes SSL cert from the app do
rake # remotely execute a rake command
console # remotely execute a single consol
console # start an interactive console to
restart # restart app servers
logs # fetch recent log output for debu
logs:cron # fetch cron log output
maintenance:on # put the app into maintenance mod
maintenance:off # take the app out of maintenance
config # display the app's config vars (e
config:add key=val [...] # add one or more config vars
config:remove key [...] # remove one or more config vars
config:clear # clear user-set vars and reset to
stack # show current stack and list of a
stack:migrate # prepare migration of this app to
db:pull [] # pull the app's database into a l
db:push [] # push a local database into the a
ase
db:reset # reset the database for the app
bundles # list bundles for the app
bundles:capture [] # capture a bundle of the app's co
bundles:download # download most recent app bundle
bundles:download # download the named bundle
bundles:animate # animate a bundle into a new app
bundles:destroy # destroy the named bundle
addons # list installed addons
addons:info # list all available addons
addons:add name [key=value] # install addon (with zero or more
addons:remove name # uninstall an addons
addons:clear # uninstall all addons
destroy # destroy the app permanently
=== Plugins
plugins # list installed plugins
plugins:install # install the plugin from the spec
plugins:uninstall # remove the specified plugin
=== Example:
rails myapp
cd myapp
git init
git add .
git commit -m "my new app"
heroku create
git push heroku master
Below are the list of available list of heroku commands
help # show this usage
version # show the gem version
list # list your apps
create [
keys # show your user's public keys
keys:add [
keys:remove
keys:clear # remove all keys
info # show app info, like web url and
open # open the app in a web browser
rename
dynos
workers
sharing:add
sharing:remove
sharing:transfer
domains:add
domains:remove
domains:clear # remove all custom domains
ssl:add
ssl:remove
rake
console
console # start an interactive console to
restart # restart app servers
logs # fetch recent log output for debu
logs:cron # fetch cron log output
maintenance:on # put the app into maintenance mod
maintenance:off # take the app out of maintenance
config # display the app's config vars (e
config:add key=val [...] # add one or more config vars
config:remove key [...] # remove one or more config vars
config:clear # clear user-set vars and reset to
stack # show current stack and list of a
stack:migrate # prepare migration of this app to
db:pull [
db:push [
ase
db:reset # reset the database for the app
bundles # list bundles for the app
bundles:capture [
bundles:download # download most recent app bundle
bundles:download
bundles:animate
bundles:destroy
addons # list installed addons
addons:info # list all available addons
addons:add name [key=value] # install addon (with zero or more
addons:remove name # uninstall an addons
addons:clear # uninstall all addons
destroy # destroy the app permanently
=== Plugins
plugins # list installed plugins
plugins:install
plugins:uninstall
=== Example:
rails myapp
cd myapp
git init
git add .
git commit -m "my new app"
heroku create
git push heroku master
Thursday, April 29, 2010
Rails application deployment with heroku
Install git
Generate RSA public and Private keys in your system
Required Gems
Heroko
Taps - By default heroku uses postgreSQL as the database, so use this gem to convert your database from mysql to postgresql.
First create an account in heroku.com website.
Open terminal and CD to the application you want to deploy
#git init
#git add .
#git commit -m 'First submit'
Till now one empty git repository (.git) created in your local application folder and save the changes in the local repository.
#heroku create appname
It will ask you the email and password which you have already signup in heroku.com and create the appname in heroku as subdomain. i.e appname.heroku.com
#git push heroku master
This command will transfer all your files from local repo to the heroku application.
Process for Database Push and Pull
#heroku rake db:migrate
This will migrate all your local db to heroku, Make sure to maintain migrations clearly
#heroku rake db:push
Sometimes you may face many problems in db migrations, so take care of db migrations. If you face problems, just us heroku db:push without heroku rake db:migrate.
#Other commands
#heroku db:pull
to pull the db from heroku
#heroku db:open
to c all heroku commands
Repeate the above process when you change any modification to the files.
Generate RSA public and Private keys in your system
Required Gems
Heroko
Taps - By default heroku uses postgreSQL as the database, so use this gem to convert your database from mysql to postgresql.
First create an account in heroku.com website.
Open terminal and CD to the application you want to deploy
#git init
#git add .
#git commit -m 'First submit'
Till now one empty git repository (.git) created in your local application folder and save the changes in the local repository.
#heroku create appname
It will ask you the email and password which you have already signup in heroku.com and create the appname in heroku as subdomain. i.e appname.heroku.com
#git push heroku master
This command will transfer all your files from local repo to the heroku application.
Process for Database Push and Pull
#heroku rake db:migrate
This will migrate all your local db to heroku, Make sure to maintain migrations clearly
#heroku rake db:push
Sometimes you may face many problems in db migrations, so take care of db migrations. If you face problems, just us heroku db:push without heroku rake db:migrate.
#Other commands
#heroku db:pull
to pull the db from heroku
#heroku db:open
to c all heroku commands
Repeate the above process when you change any modification to the files.
Monday, April 12, 2010
Make will_paginate as ajax pagination
Add below code in your public/javascripts/application.js
document.observe("dom:loaded", function() {
// the element in which we will observe all clicks and capture
// ones originating from pagination links
var container = $(document.body)
if (container) {
var img = new Image
img.src = '/images/spinner.gif'
function createSpinner() {
return new Element('img', { src: img.src, 'class': 'spinner' })
}
container.observe('click', function(e) {
if (e.element().match('img'))
var el = e.element().ancestors()[0]
else
var el = e.element()
if (el.match('.pagination a')) {
el.up('.pagination').insert(createSpinner())
new Ajax.Request(el.href, { method: 'get' })
e.stop()
}
})
}
})
In app/controllers/controller.rb file add below
def product
@similar_products = Product.paginate(:per_page => 4,:page=>params[:similar_products_page],:conditions => ["shopping_category_id = ? and id != ?", @product.shopping_category_id, @product.id])
@featureproduct = Product.paginate(:per_page =>1, :page=>params[:featureproduct_page], :conditions => ["featured = ? and id != ?", 1, @product.id], :order=>'rand()', :limit => 3)
if params[:similar_products_page]
respond_to do |format|
#format.html
format.js {
render :update do |page|
# 'page.replace' will replace full "results" block...works for this example
# 'page.replace_html' will replace "results" inner html...useful elsewhere
page.replace_html 'related', :partial => 'related_products'
end
}
end
end
if params[:featureproduct_page]
respond_to do |format|
#format.html
format.js {
render :update do |page|
# 'page.replace' will replace full "results" block...works for this example
# 'page.replace_html' will replace "results" inner html...useful elsewhere
page.replace_html 'featured', :partial => 'product_featured'
end
}
end
end
In app/views/products/_product_featured.rb
<%= will_paginate @featureproduct, :param_name => 'featureproduct_page', :prev_label => image_tag('shopping/left_arrow.jpg'), :next_label => image_tag('shopping/right_arrow.jpg'), :page_links=>false%>
In app/views/products/_related_products.rb
<%= will_paginate @similar_products,:param_name => 'similar_products_page' %>
Now your pagination become ajax.
document.observe("dom:loaded", function() {
// the element in which we will observe all clicks and capture
// ones originating from pagination links
var container = $(document.body)
if (container) {
var img = new Image
img.src = '/images/spinner.gif'
function createSpinner() {
return new Element('img', { src: img.src, 'class': 'spinner' })
}
container.observe('click', function(e) {
if (e.element().match('img'))
var el = e.element().ancestors()[0]
else
var el = e.element()
if (el.match('.pagination a')) {
el.up('.pagination').insert(createSpinner())
new Ajax.Request(el.href, { method: 'get' })
e.stop()
}
})
}
})
In app/controllers/controller.rb file add below
def product
@similar_products = Product.paginate(:per_page => 4,:page=>params[:similar_products_page],:conditions => ["shopping_category_id = ? and id != ?", @product.shopping_category_id, @product.id])
@featureproduct = Product.paginate(:per_page =>1, :page=>params[:featureproduct_page], :conditions => ["featured = ? and id != ?", 1, @product.id], :order=>'rand()', :limit => 3)
if params[:similar_products_page]
respond_to do |format|
#format.html
format.js {
render :update do |page|
# 'page.replace' will replace full "results" block...works for this example
# 'page.replace_html' will replace "results" inner html...useful elsewhere
page.replace_html 'related', :partial => 'related_products'
end
}
end
end
if params[:featureproduct_page]
respond_to do |format|
#format.html
format.js {
render :update do |page|
# 'page.replace' will replace full "results" block...works for this example
# 'page.replace_html' will replace "results" inner html...useful elsewhere
page.replace_html 'featured', :partial => 'product_featured'
end
}
end
end
In app/views/products/_product_featured.rb
<%= will_paginate @featureproduct, :param_name => 'featureproduct_page', :prev_label => image_tag('shopping/left_arrow.jpg'), :next_label => image_tag('shopping/right_arrow.jpg'), :page_links=>false%>
In app/views/products/_related_products.rb
<%= will_paginate @similar_products,:param_name => 'similar_products_page' %>
Now your pagination become ajax.
Multiple paginations in single page using will paginate
If you want to display multiple paginations in a single page then you have to change the detault page parameter. to change the default :page => params[:page] use below process
In controller add below
@featured = Product.paginate(:page => params[:featured_page])
@related = Product.paginate(:page => params[:related_page])
In view add below
<%= will_paginate @featured, :param_name => 'featured_page' %>
<%= will_paginate @related, :param_name => 'related_page' %>
In controller add below
@featured = Product.paginate(:page => params[:featured_page])
@related = Product.paginate(:page => params[:related_page])
In view add below
<%= will_paginate @featured, :param_name => 'featured_page' %>
<%= will_paginate @related, :param_name => 'related_page' %>
Tuesday, March 30, 2010
Export and import database to and from remote servers through telnet
Hi, If you want to take database backup from one server and import it into another remote server use the below process.
Import command at terminal or dos
mysql -u user_login -p database_name < /path_to_the_file/my_backup.sql
Export command at terminal or dos
mysqldump -u user_login -p database_name > /path_to_the_file/my_backup.sql
Database Backup
connect to remote host with SSH from termail using below command
#ssh user@host.com
password:
After login, crate one folder to store the backup file and make it writeble, then run the beloc ommand to take backup for the whole database
#mysqldump -u dbusername -p dbname > dbbackup.sql
It will ask you the dbpassword
After download ddbackup.sql and transfer to new host where you have to set up the database..
connect to remote host with SSH
#mysql -u dbusername -p dbname -e 'source dbbackup.sql'
It wil ask you the dbpassword.
The other way, which is even cooler, and more secure, assuming you have ssh access on both machines (this, again, is a direct dump-to-import):
mysqldump -ux -px database | ssh me@newhost "mysql -ux -px database"
This will dump the data to stdout, pipe it to ssh @ the newhost, and into mysql. Of course, replace all x's with username's and password.
If you want to keep two databases equal, you can use rsync (if your system supports it) to do it by creating a simple script:
rsync you@yourserver::share/path/to/mysql/data/* /path/on/the/other/server/
that you call with a cron job every 10 minutes/1 hour/1day/...
This way, whenever your database change, rsync will find the difference and would transfer ONLY the bytes that have changed.
Ref: http://www.webhostingtalk.com/archive/index.php/t-226992.html
Import command at terminal or dos
mysql -u user_login -p database_name < /path_to_the_file/my_backup.sql
Export command at terminal or dos
mysqldump -u user_login -p database_name > /path_to_the_file/my_backup.sql
Database Backup
connect to remote host with SSH from termail using below command
#ssh user@host.com
password:
After login, crate one folder to store the backup file and make it writeble, then run the beloc ommand to take backup for the whole database
#mysqldump -u dbusername -p dbname > dbbackup.sql
It will ask you the dbpassword
After download ddbackup.sql and transfer to new host where you have to set up the database..
connect to remote host with SSH
#mysql -u dbusername -p dbname -e 'source dbbackup.sql'
It wil ask you the dbpassword.
The other way, which is even cooler, and more secure, assuming you have ssh access on both machines (this, again, is a direct dump-to-import):
mysqldump -ux -px database | ssh me@newhost "mysql -ux -px database"
This will dump the data to stdout, pipe it to ssh @ the newhost, and into mysql. Of course, replace all x's with username's and password.
If you want to keep two databases equal, you can use rsync (if your system supports it) to do it by creating a simple script:
rsync you@yourserver::share/path/to/mysql/data/* /path/on/the/other/server/
that you call with a cron job every 10 minutes/1 hour/1day/...
This way, whenever your database change, rsync will find the difference and would transfer ONLY the bytes that have changed.
Ref: http://www.webhostingtalk.com/archive/index.php/t-226992.html
Friday, March 26, 2010
Get IP address of the site visitor in rails application
In RAILS_ROOT/app/controllers/show_my_ip_controller.rb
class ShowMyIpController < ApplicationController
def index
@client_ip = request.remote_ip
end
end
In RAILS_ROOT/app/views/show_my_ip/index.html.erb
Your IP address is <%= @client_ip %>
class ShowMyIpController < ApplicationController
def index
@client_ip = request.remote_ip
end
end
In RAILS_ROOT/app/views/show_my_ip/index.html.erb
Your IP address is <%= @client_ip %>
Thursday, March 18, 2010
Working with Float values
While you are working with float numbers and you should always want to display 1 or 2 numbers only after precission ex: You like to display 5.30 instead of 5.29088388434. To display in that format we have to use below functions
In Ruby:
f=1.23456
puts sprintf('%.2f', f).sub(/0{1,2}$/, '')
In php:
$$grandtotal = $rate*$miles;
echo number_format($grandtotal,2);
?>
In Ruby:
f=1.23456
puts sprintf('%.2f', f).sub(/0{1,2}$/, '')
In php:
$$grandtotal = $rate*$miles;
echo number_format($grandtotal,2);
?>
Friday, February 19, 2010
Cron job settings in server
Cron jobs are used to run a script automatically with some time interval Example if you want to send emails daily morining to all newsletter subscribers when new jobs were added to your jobs portal these cron jobs are used. Below are the steps to setup cron jobs
For php:
Login to hosting server and goto the cron job settings page and select the time interval you want to run the script then give the command to run the php file as below
php /path-to-your-phpfile.php
(OR)
/usr/local/bin/php /path-to-your-phpfile.php
For Ruby:
/usr/local/bin/ruby /home/user/domainname/script/runner /home/user/domainname/app/cron_job.rb
For php:
Login to hosting server and goto the cron job settings page and select the time interval you want to run the script then give the command to run the php file as below
php /path-to-your-phpfile.php
(OR)
/usr/local/bin/php /path-to-your-phpfile.php
For Ruby:
/usr/local/bin/ruby /home/user/domainname/script/runner /home/user/domainname/app/cron_job.rb
Understanding of Restful Architecture
RESTful interface means clean URLs, less code, CRUD interface.
CRUD means Create-READ-UPDATE-DESTROY.
You might heard about HTTP verbs, GET, POST. In REST, they add 2 new verbs, i.e, PUT, DELETE.
There are 7 default actions, those are – index, show, new, create, edit, update, destroy
GET is used when you retrieve data from database. POST is used when you create new record in database. PUT is used when you are updating any existing record in database, and DELETE is used when you are destroying any record in database. Following table may clear the concept.
Action VERB
index GET
show GET
new GET
create POST
edit GET
update PUT
destroy DELETE
CRUD means Create-READ-UPDATE-DESTROY.
You might heard about HTTP verbs, GET, POST. In REST, they add 2 new verbs, i.e, PUT, DELETE.
There are 7 default actions, those are – index, show, new, create, edit, update, destroy
GET is used when you retrieve data from database. POST is used when you create new record in database. PUT is used when you are updating any existing record in database, and DELETE is used when you are destroying any record in database. Following table may clear the concept.
Action VERB
index GET
show GET
new GET
create POST
edit GET
update PUT
destroy DELETE
Monday, February 15, 2010
All about Ajax and its states
Ajax (Asynchronous Javascript And XML) is used to update part of the webpage's content Asynchronously without reloading the entire page. Below are the five possible response states in Ajax
0: The request is uninitialized (before you've called open()).
1: The request is set up, but not sent (before you've called send()).
2: The request was sent and is in process (you can usually get content headers from the response at this point).
3: The request is in process; often some partial data is available from the response, but the server isn't finished with its response.
4: The response is complete; you can get the server's response and use it.
0: The request is uninitialized (before you've called open()).
1: The request is set up, but not sent (before you've called send()).
2: The request was sent and is in process (you can usually get content headers from the response at this point).
3: The request is in process; often some partial data is available from the response, but the server isn't finished with its response.
4: The response is complete; you can get the server's response and use it.
About ORM (Object Relation Mapping)
Accessing database using a layer of classes is called ORM. The rest of the application uses these classes and their objects. It never allow directly interacting with database.
1. ORM libraries map database tables to classes. If a database has a table users(plural).Our program will have a class named user(singular) stored in model folder,
2. Rows in this table correspond to objects of the class—a particular user is represented as an object of class user.
3. By using this object's attributes we can set and get the individual columns.
So an ORM layer maps tables to classes, rows to objects and columns to attributes of that object(methods).
Class methods are used to perform table-level operations.
Instance methods are used to perform operations on the individual rows.
It is all taken care by ActiveRecord class.
1. ORM libraries map database tables to classes. If a database has a table users(plural).Our program will have a class named user(singular) stored in model folder,
2. Rows in this table correspond to objects of the class—a particular user is represented as an object of class user.
3. By using this object's attributes we can set and get the individual columns.
So an ORM layer maps tables to classes, rows to objects and columns to attributes of that object(methods).
Class methods are used to perform table-level operations.
Instance methods are used to perform operations on the individual rows.
It is all taken care by ActiveRecord class.
Friday, February 12, 2010
Generating rsa public and private keys in linux
Open terminal and run ssh-keygen with below optional params
$ ssh-keygen -t rsa -C "venkatadapa@gmail.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/home/venkat/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/venkat/.ssh/id_rsa.
Your public key has been saved in /home/venkat/.ssh/id_rsa.pub.
The key fingerprint is:
01:0f:f4:3b:ca:85:d6:17:a1:7d:f0:68:9d:f0:a2:db venkatadapa@gmail.com
Use "ssh-add path/to/my_key" If you want to change the path of the keys to store at Your public key has been saved in /home/venkat/.ssh/id_rsa.pub.
To know more about passphrases just visit http://help.github.com/working-with-key-passphrases/
After finished the above steps an hidden .ssh folder was created in that specified path containing with files id_rsa,id_rsa.pub and known_hosts. id_rsa contains private key. id_rsa_pub contains your public key.
You can use this key for your github account to manage your data from your computer.
$ ssh-keygen -t rsa -C "venkatadapa@gmail.com"
Generating public/private rsa key pair.
Enter file in which to save the key (/home/venkat/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/venkat/.ssh/id_rsa.
Your public key has been saved in /home/venkat/.ssh/id_rsa.pub.
The key fingerprint is:
01:0f:f4:3b:ca:85:d6:17:a1:7d:f0:68:9d:f0:a2:db venkatadapa@gmail.com
Use "ssh-add path/to/my_key" If you want to change the path of the keys to store at Your public key has been saved in /home/venkat/.ssh/id_rsa.pub.
To know more about passphrases just visit http://help.github.com/working-with-key-passphrases/
After finished the above steps an hidden .ssh folder was created in that specified path containing with files id_rsa,id_rsa.pub and known_hosts. id_rsa contains private key. id_rsa_pub contains your public key.
You can use this key for your github account to manage your data from your computer.
Tuesday, February 9, 2010
Conditional assignment operator in Ruby
Hi, ||= is an operator for assigning value to a variable conditionally in Ruby. See the example below
Here a @secrete is an instance variable contains array of four values. End user guess that values along with the order
If value found and at same position you will see T, If found but not at same position output is 't'. If your guessed value is not at all in the @secrete list your output is F
<%
@secret = %w[chiru ballaya nag venki]
def guess(guess) #where guess is an array of having four values
result = [nil,nil,nil,nil] #array with four nil values
guess.each_with_index do |value, index|
if @secret[index] == value
result[index] = "T"
elsif @secret.include?(value)
result[@secret.index(value)] ||= "t" # ||= is conditional assignment operator, means which will only assign the value if it is currently nil or false. It will not replace if it is already have any value in that variable.
end
end
result.compact.sort.join
end
end
end
guess(%w[chiru nag ballay venki]) #here you are guessing the names and orders.
%>
#output TttT
#Chiru and Venki are exists and also at same positions.
#nag and ballayya are exists but not at same positions.
Here a @secrete is an instance variable contains array of four values. End user guess that values along with the order
If value found and at same position you will see T, If found but not at same position output is 't'. If your guessed value is not at all in the @secrete list your output is F
<%
@secret = %w[chiru ballaya nag venki]
def guess(guess) #where guess is an array of having four values
result = [nil,nil,nil,nil] #array with four nil values
guess.each_with_index do |value, index|
if @secret[index] == value
result[index] = "T"
elsif @secret.include?(value)
result[@secret.index(value)] ||= "t" # ||= is conditional assignment operator, means which will only assign the value if it is currently nil or false. It will not replace if it is already have any value in that variable.
end
end
result.compact.sort.join
end
end
end
guess(%w[chiru nag ballay venki]) #here you are guessing the names and orders.
%>
#output TttT
#Chiru and Venki are exists and also at same positions.
#nag and ballayya are exists but not at same positions.
Subscribe to:
Posts (Atom)