Friday, February 4, 2011

How to find the name of the current Rake task


A few weeks ago I needed a Rake task to answer a simple question for me:
“What’s my name?”
I honestly can’t quite remember why exactly the task needed to know it’s own name, but at the time it seemed important and I spent a couple hours digging about before I found out that Rake tasks are shy by nature. Or at least when implemented the way almost every tutorial tells you to implement them:
namespace :life do

desc "The answer to life, the universe, and everything"
task :answer do
puts "The answer to life, the universe, and everything is 42."
end

end
But how do I know what the name of the current task is? Well, after making a couple of random attempts (like “puts task.name”) and digging around in the very sparsedocumentation on the Rake homepage, I stumbled across a bit of documentation that talked about “Tasks with Actions”:
Actions are defined by passing a block to the task method. Any Ruby code can be placed in the block. The block may reference the task object via the block parameter.
task :name => [:prereq1, :prereq2] do |t|
# actions (may reference t)
end
Ah ha! “The block may reference the task object via the block parameter.” That’s exactly what I was looking for. Adding the block parameter allows us to reference the task object itself. And the task object itself has a good bit of useful meta information:
namespace :life do

desc "The answer to life, the universe, and everything"
task :answer do |t|
puts t.name
puts t.comment
puts t.scope
end

end
The task now returns the following:
life:answer
The answer to life, the universe, and everything
life
The first line of output is nifty, and answers the “What’s my name?” question with the fully scoped name of the task. Given that much it’s probably not hard to return the task name in even the most deeply namespaced Rakefile. The second line is the “comment” — actually the description of the task. And the third line gets us the scope (namespaces). There are more methods available, but check teh googles for “Rake::Task api”.
So with this meta information we can do something useful like:
namespace :life do

desc "The answer to life, the universe, and everything"
task :answer do |t|
puts "#{t.comment} is 42."
end

end

How to dynamically update form elements in Rails using Ajax


Here’s the situation: You have two SELECT elements on a form. When the user chooses an item out of the first SELECT element, the contents of the second SELECT element need to change and show different values based on the initial selection.
This used to take quite a bit of JavaScript wizardry. But it’s pretty straightforward in Rails using a bit of Ajax. Here’s how:
First, make sure you’re including the Ajax libraries (Prototype, script.aculo.us, etc.) in your layout like so:
       <%= javascript_include_tag :defaults %>


...
Next, create a form with your initial SELECT, and empty second SELECT, and set up field observer. Here’s a really simple example:




<%= observe_field "states", :update => "cities",
:with => "city_id", :url => { :controller => "test",
:action => "get_cities" } %>






Finally, you’ll need to set up a method to handle the call from the observer and a corresponding view page to generate the HTML content that will replace everything betwen the SELECT tags in the second SELECT. Here’s an example "get_cities" controller:
def get_cities
@cities = City.find_by_state(:all)
end
And an example "get_cities.rhtml" file:
<% for city in @cities %>

<% end %>
And there you go. This much should dynamically update the "cities" SELECT element with new content every time the "onchange" event is fired on the initial "states" SELECT form element.

How to define multiple users in a Capistrano deployment file


We’re just starting to get into Ruby on Rails at my work, and we’re close to deploying our first application to a production server with Capistrano.
Capistrano makes it easy for developers to deploy code to the production server from their own workstations. But we quickly ran into two problems:
  1. It’s often the case that a developer’s username on their local workstation is different from their username on the production server. This requires you to set the developer’s server username in the “deploy.rb” file. Hard-coded.
  2. Hard-coding a single username makes it difficult for multiple users to share a “deploy.rb” file.
Well, it turns out that Capistrano is better than all that. With a little bit of conditional logic and the ability for Cap to read environment variables, the problem is solved like this in the “deploy.rb” file:
if ENV["USER"] == "robert"
set :user, "bob"
elsif ENV["USER"] == "elizabeth"
set :user, "beth"
end

How to create Rails scaffolds and database tables dynamically


The idea I’m exploring here is whether or not we can build a CMS (content management system) in Ruby on Rails that can dynamically build a CMS. In other words, can we write Rails code that writes Rails code.
It seems we can. This is pretty awesome, and somewhat frightening, because it apparently works. Here’s a method in, say, a “utils_controller.rb”:
def generate_scaffold
@results = `script/generate scaffold
Things name:string value:string`
end
Note the use of backticks around the shell commands to generate a scaffold. If you run that method in your browser, it actually generates the controller, model, migration, etc.
Then do this:
def migrate
@results = `rake db:migrate`
end
Yep. Now you just migrated the database and have new “things” table.

How to find your Ruby gem installation path


You can find the location or path to where your Ruby gems are installed at with this command:
gem environment gemdir

Thursday, February 3, 2011

Remote Desktop (Remote Login) Ubuntu

vino is VNC server for GNOME.VNC is a protocol that allows remote display of a user’s desktop. This package provides a VNC server that integrates with GNOME, allowing you to export your running desktop to another computer for remote use or diagnosis.
By default ubuntu will come with vino-server so it is very easy to configure to enable remote desktop sharing in your ubuntu machine.If you want to access ubuntu machine remotely you need to login in to your ubuntu system.
Important note :-
Remote Desktop will only work if there’s a GNOME login session.Leaving your computer with an unattended GNOME login session is not secure and not recommended.
Some Tips
1) You can lock your screen using System--->Quit
Once you click on quit you should see the following screen here you need to select lockscreen
2) switch off your monitor when computer is left unattended
Configuring Remote Desktop
First you need to go to System -> Preferences -> Remote Desktop
Once it opens you should see the following screen
In the above screen you need to configure remote desktop preferences for sharing and security
For Sharing
you need to tick the box next to the following two options
Allow other users to view your desktop
Allow other users to control your desktop
For Security
you need to tick the box next to the following two options
Ask you for confirmation (If you tick this option some one need to click on allow from remote desktop once it connected if you don’t want you can untick this option)
Require the user to enter this password:
Password: Specify the password
Connecting from Ubuntu Machine
Open your terminal from Applications--->Accessories--->Terminal and enter the following command
vncviewer -fullscreen 192.168.2.23:0
now you should see the following message asking for password enter the password after complete success you can see VNC authentication succeeded message and starting remote desktop
VNC viewer version 3.3.7 - built Jul 4 2006 10:04:48
Copyright (C) 2002-2003 RealVNC Ltd.
Copyright (C) 1994-2000 AT&T Laboratories Cambridge.
See http://www.realvnc.com for information on VNC.
VNC server supports protocol version 3.7 (viewer 3.3)
Password:
VNC authentication succeeded
If you want to quit vncviewer
Press ‘F8′ and select Quit viewer
Connecting from Windows machine
If you are trying to connect from your windows machine you need to install vncviewer of your choice i have installed from here http://www.realvnc.com/download.html.Install this program once you install this you can opem from start--->All programs--->RealVNC--->VNC Viewer 4--->Run VNC Viewer once it opens you should see the following screen here enter the remotemachine ipaddress:0 format and click ok
Now it will prompt for password enter your password and click ok
Now on the remote machine you should see the following screen asking for permission to allow this connection you need to click on allow this will comeup only if you tick “Ask you for confirmation” option under sharing
Once it connected you should see the remote machine desktop like the following screen

How to turn a string into CamelCase in Ruby


Below are the few tricks to capitalize only the first letter of each word of a multi word string.
def wikify(phrase)
phrase.gsub!(/^[a-z]|\s+[a-z]/) { |a| a.upcase }
phrase.gsub!(/\s/, '')
return phrase
end
This turns “my dog has fleas” into “MyDogHasFleas”.


If you’re in Rails, you can take advantage of the Inflector class and do something like this:
>> phrase = ‘my Dog hAs FlEas’
=> “my Dog hAs FlEas”
>> phrase.downcase.gsub(/\s/, ‘_’).camelize
=> “MyDogHasFleas”
I only know this because the inflector’s “titleize” method is great if you want to “capitalize” multi-word phrases.


def wikify(phrase)
phrase.downcase.gsub(/\b[a-z]/) { |a| a.upcase }.gsub(/\s/, ”)
end

  'some string here'.gsub(/\b\w/){$&.upcase}
>> Some String Here