Step-By-Step setup slicehost server (fedora) for rails application.

Posted by Bhushan Ahire | Posted in capistrano, Rails, Subversion | Posted on 22-07-2009

1

Get location from IP address in Ruby On Rails for free….

Posted by Bhushan Ahire | Posted in Rails, ruby, Security | Posted on 20-05-2009

0

Find below the code for finding location from IP address using IP location tools.

require 'net/http'
require 'rexml/document'
include REXML

class MapsController < ApplicationController
	def index
		@location = locateIp()

	end

	def locateIp
		ip = request.remote_ip
		ips = ip.to_s
		url = "http://iplocationtools.com/ip_query.php?ip="+ips

		xml_data = Net::HTTP.get_response(URI.parse(url)).body

                xmldoc = REXML::Document.new(xml_data)

		# Now get the root element
		root = xmldoc.root
		city = ""
		regionName = ""
		countryName = ""

		# This will take country name...
		xmldoc.elements.each("Response/CountryName") {
		|e| countryName << e.text
	    }

		# Now get city name...
		xmldoc.elements.each("Response/City") {
   		|e| city << e.text
	    }

		# This will take regionName...
		xmldoc.elements.each("Response/RegionName") {
   		|e| regionName << e.text
	    }

     	ipLocation = city +", "+regionName+", "+countryName

	 return ipLocation
   end #end of method locateIp

end

Generating ZIP files via Ruby on Rails using rubyzip

Posted by Bhushan Ahire | Posted in Rails, ruby | Posted on 03-03-2009

2

gem install rubyzip

Then, in the model that I’m using to generate the zip bundles, I add a couple “require” statements:

require 'zip/zip'
require 'zip/zipfilesystem'

class Album < ActiveRecord::Base
  (...)
end

Next, I added a class method called bundle, which when called will use rubygem to generate the zip file. Note: the “permalink” attributes of Album and Artist are populated when an object of those models is created. I’m using them because it makes for nice filenames, too.

# create a zipped archive file of all the tracks in an album
def bundle(name = self.permalink, set = self.artist.permalink)
   bundle_filename = "#{RAILS_ROOT}/public/uploads/#{set}-#{name}.zip"

   # check to see if the file exists already, and if it does, delete it.
   if File.file?(bundle_filename)
     File.delete(bundle_filename)
   end

   # set the bundle_filename attribute of this object
   self.bundle_filename = "/uploads/#{set}-#{name}.zip"

   # open or create the zip file
   Zip::ZipFile.open(bundle_filename, Zip::ZipFile::CREATE) {
     |zipfile|
     # collect the album's tracks
     self.tracks.collect {
       |track|
         # add each track to the archive, names using the track's attributes
         zipfile.add( "#{set}/#{track.num}-#{track.filename}", "#{RAILS_ROOT}/public#{track.public_filename}")
       }
   }

   # set read permissions on the file
   File.chmod(0644, bundle_filename)

   # save the object
   self.save
end

Next I added a method in my controller:

def create_bundle
   album = Album.find(params[:id])
   album.bundle
   flash[:notice] = 'Album was successfully zipped.'
   redirect_to album_url(album.artist, album)
end

And edit my routes.rb accordingly:

map.create_bundle 'create_bundle/:id', :controller => 'albums', :action => 'create_bundle'

Now it’s just a matter of creating a link in the view for the admin to click whenever he/she wants to generate the zip file:

<%= link_to('Create Album Zip', create_bundle_path(@album)) %>

…and a link for the user to click to download the zip file if it exists:

<% unless @album.bundle_filename.nil? %>
<%= link_to "Download Album Zip", @album.bundle_filename %>
<% end %>

That’s it! Refer to the rubyzip documentation for more info.

Keep either file in merge conflicts with git

Posted by Bhushan Ahire | Posted in git, Rails | Posted on 26-02-2009

0

So, the scenario is: you’re in the middle of a merge, and you want to keep one file or the other.

$ git merge master
Auto-merged _layouts/default.html
CONFLICT (content): Merge conflict in _layouts/default.html
Auto-merged index.html
CONFLICT (content): Merge conflict in index.html
Automatic merge failed; fix conflicts and then commit the result.

There’s two unmerged files here. According to the git checkout manpage, there’s a --theirs and --ours options on the command. The former will keep the version of the file that you merged in, and the other will keep the original one we had.

The following commands will keep the original file for index.html, and then use the merged in file only for _layouts/default.html.

git checkout –ours index.html
git checkout –theirs _layouts/default.html

Sadly, these options are only in Git versions 1.6.1 and up. If you have an older version and don’t feel like upgrading, there’s ways to get around this. To emulate --theirs, we’d do:

git reset — _layouts/default.html
git checkout MERGE_HEAD — _layouts/default.html

And for --ours:

git reset — index.html
git checkout ORIG_HEAD — index.html

Of course, once you’ve got the conflicts worked out, git add whatever changes need to be added in, and git commit away. If you’ve run into other problems with merging that could possibly help out others, comment away!



referred from http://gitready.com/advanced/2009/02/25/keep-either-file-in-merge-conflicts.html

Setting up a new remote git repository

Posted by Bhushan Ahire | Posted in git, Rails | Posted on 19-02-2009

2

For the impatient

Set up the new bare repo on the server:

$ ssh myserver.com
Welcome to myserver.com!
$ mkdir /var/git/myapp.git && cd /var/git/myapp.git
$ git --bare init
Initialized empty Git repository in /var/git/myapp.git
$ exit
Bye!

Add the remote repository and push:

$ cd ~/Sites/myapp
$ git remote add origin ssh://myserver.com/var/git/myapp.git
$ git push origin master

Set the local master branch to track the remote branch.

Read further for a step-by-step explanation of what’s going on.

Pre-flight sanity check

Setting up a remote repository is fairly simple but somewhat confusing at first. Firstly, let’s check out what remote repositories are being tracked in our git repo:

$ cd ~/Sites/myapp
$ git remote

None. Looking good. Now let’s list all the branches:

$ git branch -a
* master

Just one branch, the master branch. Let’s have a look at .git/config:

$ cat .git/config
[core]
        repositoryformatversion = 0
        filemode = true
        bare = false
        logallrefupdates = true

A pretty bare-minimum config file.

Creating the bare remote repository

Before we can push our local master branch to a remote repository we need to create the remote repository. To do this we’ll ssh in and create it on the server:

$ ssh myserver.com
Welcome to myserver.com!
$ cd /var/git
$ mkdir myapp.git
$ cd myapp.git
$ git --bare init
Initialized empty Git repository in /var/git/myapp.git
$ exit
Bye!

A short aside about what git means by bare: A default git repository assumes that you’ll be using it as your working directory, so git stores the actual bare repository files in a .git directory alongside all the project files. Remote repositories don’t need copies of the files on the filesystem unlike working copies, all they need are the deltas and binary what-nots of the repository itself. This is what “bare” means to git. Just the repository itself.

Adding the remote repository to our local git repository configuration

Now that we’ve created the remote repository we’ll add it to our local repository as a remote server called “origin” using git remote add, which is just a nicer way of updating our config file for us:

$ git remote add origin ssh://myserver.com/var/git/myapp.git

Let’s see what it added to the config file:

[core]
  repositoryformatversion = 0
  filemode = true
  bare = false
  logallrefupdates = true
[remote "origin"]
  url = ssh://myserver.com/var/git/myapp.git
  fetch = +refs/heads/*:refs/remotes/origin/*

We now have a remote repository “origin” that will fetch all of it’s refs/heads/* branches and store them in our local repo in refs/remotes/origin/* when a git fetch is performed.

Pushing to the remote repository

The time has come to push our local master branch to the origin’s master branch. We do that using the git push command.

$ git push origin master
updating 'refs/heads/master'
  from 0000000000000000000000000000000000000000
  to   b379203bc187c2926f44a71eca3f901321ea42c6
 Also local refs/remotes/origin/master
Generating pack...
Done counting 1374 objects.
Deltifying 1374 objects...
 100% (1374/1374) done
Writing 1374 objects...
 100% (1374/1374) done
Total 1374 (delta 89), reused 0 (delta 0)
refs/heads/master: 0000000000000000000000000000000000000000 -> b379203bc187c2926f44a71eca3f901321ea42c6

and that’s all, folks. Further pushes can be done by repeating the git push command.

Now you can tell your co-conspirators to:

$ git clone ssh://myserver.com/var/git/myapp.git

and push and pull to your heart’s content.

Track the remote branch

You can specify the default remote repository for pushing and pulling using git-branch’s track option. You’d normally do this by specifying the --track option when creating your local master branch, but as it already exists we’ll just update the config manually like so:

[branch "master"]
  remote = origin
  merge = refs/heads/master

Now you can simply git push and git pull.

Sharing the remote repository with the world

If you want to set it up as a public repository be sure to check out the Git manual’s chapter on public git repositories.

Working with remote repository branches

git remote show is used to inspect a remote repository. It goes and checks the remote repository to see what branches have been added and removed since the last git fetch.

Doing a git remote show at the moment only shows us the remote repo’s master branch which we pushed earlier:

$ git remote show origin
* remote origin
  URL: ssh://myserver.com/var/git/myapp.git
  Tracked remote branches
    master

Let’s create a new local git repository and push to a new branch on the remote repository. We can then use git remote show to see the new remote branch, git fetch to mirror it into our local repo and git checkout --track -b to create a local branch to do some work on it.

We’ll start by creating a new local repo and pushing some code to a new branch in the remote repository.

$ mkdir /tmp/other-git
$ cd /tmp/other-git
$ git init
Initialized empty Git repository in /tmp/other-git
$ git remote add origin ssh://myserver.com/var/git/myapp.git
$ echo "Rails 2... woo" > afile
$ git add afile
$ git commit -m "Added afile" 
Created initial commit 0ac9a74: Added afile
 1 files changed, 1 insertions(+), 0 deletions(-)
 create mode 100644 something
$ git push origin master:refs/heads/dev/rails-2
updating 'refs/heads/rails-2' using 'refs/heads/master'
  from 0000000000000000000000000000000000000000
  to   0ac9a7457f4b21c9e058d4c54d262584bf35e528
 Also local refs/remotes/origin/rails-2
Generating pack...
Done counting 3 objects.
Deltifying 3 objects...
 100% (3/3) done
Writing 3 objects...
 100% (3/3) done
Total 3 (delta 0), reused 0 (delta 0)
Unpacking 3 objects...
 100% (3/3) done
refs/heads/rails-2: 0000000000000000000000000000000000000000 -> 0ac9a7457f4b21c9e058d4c54d262584bf35e528

Now let’s switch back to our old git repository and see if it detects the new branch on the remote repository:

$ git remote show origin
* remote origin
  URL: ssh://myserver.com/var/git/myapp.git
  New remote branches (next fetch will store in remotes/origin)
    dev/rails-2
  Tracked remote branches
    master

Let’s update our mirror of the remote repository by doing a git fetch:

$ git fetch
* refs/remotes/origin/master: storing branch 'dev/rails-2' of ssh://myserver.com/var/git/myapp.git
  commit: b379203
$ git remote show origin
* remote origin
  URL: ssh://myserver.com/var/git/myapp.git
  Tracked remote branches
    master
    dev/rails-2

We should now be able to see this in a our list of remote branches:

$ git branch -a
* master
origin/dev/rails-2
origin/master

If we then wanted to do some work on this remote dev/rails-2 branch we create a new local tracking branch like so:

$ git checkout --track -b dev/rails-2 origin/dev/rails-2
Branch dev/rails-2 set up to track remote branch refs/remotes/origin/dev/rails-2.
Switched to a new branch "dev/rails-2"

To keep up-to-date and push new changesets we simply use git push and git pull when working in the local dev/rails-2 branch.

Also notice, like we manually changed for master, .git/config has a new entry for this new tracking branch:

[branch "dev/rails-2"]
  remote = origin
  merge = refs/heads/dev/rails-2

make_resourceful for rails

Posted by Bhushan Ahire | Posted in Rails, ruby | Posted on 23-06-2008

0

The make_resourceful plugin is a great way to DRY up the 7 RESTful actions common in most controllers. Learn how to use it in this episode.
Tags:

plugins

Resources

script/plugin install http://svn.hamptoncatlin.com/make_resourceful/tags/make_resourceful
# products_controller.rb
make_resourceful do
actions :all

response_for :show do |format|
format.html
format.xml { render  :x ml => current_object.to_xml }
end
end

private

def current_objects
   Product.find(:all,  :o rder => 'name')
end

def current_object
   @current_object ||= Product.find_by_permalink(params[:id])
end
<!-- edit.html.erb -->
<%= hidden_field_tag '_flash[notice]', "Successfully updated product." %>

Audit site using acts_as_audited plugin

Posted by Bhushan Ahire | Posted in acts_as_audited, Rails | Posted on 17-05-2008

0

acts_as_audited is an Active Record plugin that logs all modifications to your models in an audits table. It uses a polymorphic association to store an audit record for any of the model objects that you wish to have audited. The audit log stores the model that the change was on, the “action” (create, update, destroy), a serialzied hash of the changes, and optionally the user that performed the action.

Auditing in Rails

NOTE: read the caveats section if the following isn’t working.

If you’re using acts_as_audited within Rails, you can simply declare which models should be audited. acts_as_audited can also automatically record the user that made the change if your controller has a current_user method.

class ApplicationController < ActionController::Base

audit User, List, Item
protected
def current_user
@user ||= User.find(session[:user])

end
end

Caveats

Auditing with user support depends on Rails’ caching mechanisms, therefore auditing isn’t enabled during development mode. To test that auditing is working, start up your app in production mode, or change the following options in config/environments/development.rb:

config.cache_classes = true

config.action_controller.perform_caching = true

Customizing

To get auditing outside of Rails, or to customize which fields are audited within Rails, you can explicitly declare acts_as_audited on your models. The :except option allows you to specify one or more attributes that you don’t want to be saved in the audit log.

class User < ActiveRecord::Base
acts_as_audited :except => [:password, :credit_card_number]

end

Installation

You can grab the plugin by running:

script/plugin install http://source.collectiveidea.com/public/rails/plugins/acts_as_audited

Run the migration generator and migrate to add the audits table.

script/generate audited_migration add_audits_table
rake db:migrate

Upgrading

Those upgrading from version 0.2 need to add 2 fields the audits table:

add_column :audits, :user_type, :string
add_column :audits, :username, :string

May this information fulfills your requirement… ;-)

Sort array of ActiveRecord object without querying to database.

Posted by Bhushan Ahire | Posted in Rails, ruby | Posted on 13-05-2008

0

Sometimes it may happen you want to sort the array of objects, fetched from ActiveRecord.

e.g. I have a users table having name column after I done any manipulation on the fetched object.

You can just call the following code for doing the above stuff.

@users = User.find :all
@users = @users – xyz_obj.users #remove existing users.
@users = @users.sort_by { |user| user[:name] }

May this code helps anyone….

Thanks ;-)

How to raise and rescue Exceptions in Ruby on Rails

Posted by Bhushan Ahire | Posted in Rails, ruby | Posted on 09-05-2008

0

Creating the Exception class

To create our “PersonalException” we just need to extend “Exception” class.


class PersonalException < Exception
end

Raise our Exception


raise PersonalException.new, "message"

Rescue our exception

We can do this by overwriting rescue_action_in_public and local_request? functions to our application.rb file:

Send mail after capistrano deployment

Posted by Bhushan Ahire | Posted in capistrano, Rails | Posted on 07-05-2008

0

I got a very good plugin at http://code.google.com/p/capistrano-mailer/.
Just copied the details below to have use in future.

It is a Capistrano Plugin AND a Rails Plugin

Ever wanted to be emailed whenever someone on the team does a cap deploy of trunk or some tag to some server. Wouldn’t it be nice to know about it every time a release was deployed? For large rails projects this type of coordination is essential, and this plugin makes sure everyone on the need to know list is notified when something new is deployed.

This plugin is an extension to Capistrano.

That means it registers itself with Capistrano as a plugin and is therefore available to call in your recipes.

If you are looking to roll your own email integration into capistrano then try this pastie: http://pastie.org/146264 (thanks to Mislav Marohni?). But if you want to take the easy road to riches then keep reading ;)

– figurative “riches” of course, I promise nothing in return for your using this plugin

Requirements

  • Rails 2.0.2
  • Capistrano 2.1.0 – 2.2.0

Installation

./script/plugin install http://capistrano-mailer.googlecode.com/svn/trunk/capistrano_mailer

Usage

1. Install the plugin.

2. Add this line to the top of your deploy.rb:

require 'vendor/plugins/capistrano_mailer/lib/capistrano_mailer'

3. Add a cap_mailer_settings.rb file to your config/ directory:

require 'vendor/plugins/capistrano_mailer/lib/cap_mailer'

ActionMailer::Base.delivery_method = :smtp
ActionMailer::Base.smtp_settings = {
:address        => "mail.default.com",
:port           => 25,
:domain         => 'default.com',
:perform_deliveries => true,
:user_name      => "releases@default.com",
:password       => "mypassword",
:authentication => :login }
ActionMailer::Base.default_charset = "latin1"

CapMailer.template_root = "vendor/plugins/capistrano_mailer/views/"
CapMailer.recipient_addresses = ["dev1@default.com"]
CapMailer.sender_address = %("Capistrano Deployment" <releases@default.com>)
CapMailer.email_prefix = "[MYSITE-CAP-DEPLOY]"
CapMailer.site_name = "MySite.com"
CapMailer.email_content_type = "text/html"

4. Add these two tasks to your deploy.rb:

namespace :show do
desc "Show some internal Cap-Fu: What's mah NAYM?!?"
task :me do
set :command, task_call_frames.first.task.fully_qualified_name
puts "Running #{command} task"
end
end

namespace :deploy do
...

desc "Send email notification of deployment"
task :notify, :roles => :app do
show.me
mailer.send(rails_env, repository, command, deploy_to, host)
end

...
end

Make sure you’ve defined rails_env, repository, deploy_to and host. command is defined by the show:me task above.

The only required parameters to mailer.send are rails_env, repository, command and deploy_to. The complete set of possible parameters is:

mailer.send(rails_env, repository, command, deploy_to, host = nil, ip_address = nil, output = nil)

If anyone has a cool way of recording the output into a capistrano accessible variable, so that it can be shoved into the release email that would be an excellent contribution!

5. Then add the hook somewhere in your deploy.rb:

after "deploy", "deploy:notify"

6. Enjoy and Happy Capping!