Cheat — Ruby Gem

July 8, 2008

Cheat:

Very useful to view cheat sheet of like following things….

association_methods
asunit
authorizenet
autotest
averylongnamethatwecanfind
awk

Installation:

gem install cheat

How to use:

cmd prompt> cheat sheets

It gives lot of outputs. You are able to view all those cheat sheets from command prompt

Ex.

C:\>cheat migrations
migrations:
Methods:
create_table(name, options)
drop_table(name)
rename_table(old_name, new_name)
add_column(table_name, column_name, type, options)
rename_column(table_name, column_name, new_column_name)
change_column(table_name, column_name, type, options)
remove_column(table_name, column_name)
add_index(table_name, column_name, index_type)
remove_index(table_name, column_name)

Available Column Types:
* integer
* float
* datetime
* date
* timestamp
* time
* text
* string
* binary
* boolean
* decimal :precision, :scale

Valid Column Options:
* limit
* null (i.e. “:null => false” implies NOT NULL)
* default (to specify default values)
* :decimal, :precision => 8, :scale => 3

Rake Tasks:
rake db:schema:dump: run after you create a model to capture the schema.rb
rake db:schema:import: import the schema file into the current database (on
error, check if your schema.rb has “:force => true” on the create table
statements
./script/generate migration MigrationName: generate a new migration with a
new ‘highest’ version (run ‘./script/generate migration’ for this info at
your fingertips)
rake db:migrate: migrate your current database to the most recent version
rake db:migrate VERSION=5: migrate your current database to a specific
version (in this case, version 5)
rake db:rollback: migrate down one migration
rake db:rollback STEP=3: migrate down three migrations
rake db:migrate RAILS_ENV=production: migrate your production database

SQL:
Queries can be executed directly:
execute ‘ALTER TABLE researchers ADD CONSTRAINT fk_researchers_departments
FOREIGN KEY ( department_id ) REFERENCES departments( id )’

Example Migration:
class UpdateUsersAndCreateProducts < ActiveRecord::Migration
def self.up
rename_column “users”, “password”, “hashed_password”
remove_column “users”, “email”

User.reset_column_information
User.find(:all).each{|u| #do something with u}

create_table “products”, :force => true do |t|
t.column “name”, :text
t.column “description”, :text
t.column “price”, :decimal, :precision => 9, :scale => 2
end

#the rails 2.0 way:
create_table :people do |t|
t.integer :account_id
t.string  :first_name, :last_name, :null => false
t.text    :description
t.timestamps
end
end

def self.down
rename_column “users”, “hashed_password”, “password”
add_column “users”, “email”, :string
drop_table “products”
end
end

Find Highest version:
script/runner “puts ActiveRecord::Migrator.current_version”

C:\>

For more details,

http://cheat.errtheblog.com/

http://errtheblog.com/posts/21-cheat

Permutation - Ruby

July 7, 2008

Permutation:

This class has a dual purpose: It can be used to create permutations of a given size and to do some simple computations with/on permutations.

The instances of this class don’t require much memory because they don’t include the permutation as a data structure. They only save the information necessary to create the permutation if asked to do so.

STEP1: In case you are using Ruby 1.8.6 and previous versions then

Installation:

The library can be installed via rubygems:

c:\gem install permutation

Sample code:

require ‘Permutation’
perm = Permutation.new(3)
perm.map { |p| p p.value }
colors = [:r, :g, :b]
perm.map { |p| p p.project(colors) }
string = “abc”
perm.map { |p| p p.project(string) }

Output:

[0, 1, 2]
[0, 2, 1]
[1, 0, 2]
[1, 2, 0]
[2, 0, 1]
[2, 1, 0]
[:r, :g, :b]
[:r, :b, :g]
[:g, :r, :b]
[:g, :b, :r]
[:b, :r, :g]
[:b, :g, :r]
“abc”
“acb”
“bac”
“bca”
“cab”
“cba”

STEP 2:

If you are using Ruby 1.8.7 and above then no need to install the gem.

CODE:

[1,2,3].permutation(3){|x| p x}

Output:

[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 1, 2]
[3, 2, 1]

Active Scaffold

Active scaffold is rails plugin used for,

Create,Edit,Update,delete,Search and sorting records in Ajax.

If you want to install it in your rails application then,

1. Please follow this url –> Active Scaffold

2. Install git in your computer –> Git

Selenium Grid

July 5, 2008

Selenium Grid:

Selenium Grid allows you to run Selenium tests in parallel, cutting down the time required for running acceptance tests to a fraction of the total time it currently takes. Run them all on a single machine (we’ve run up to 15 parallel processes on a laptop!) or on a server farm.

Technical Mumbo Jumbo:
Selenium Grid runs on top of Selenium Remote Control. Selenium is a test tool that allows you to write automated web application UI tests in any programming language against any HTTP website using any mainstream JavaScript-enabled browser.

Step 1: Download selenium grid

Step 2: Setup your environment

In case you face any path issues then set path into syatem following ways.

Way1:

Windows XP SP2 –>  1. Right click “My Computer”

2. Click “Advanced” tab

3.  Click “Environment variables” buton

4. In System variables –> clcik path –> Click edit

5. In edit system variable window –> go to end of line In “variable value” field –> [PASTE YOUR PATH]

Ex; C:\Program Files\Java\jdk1.6.0_06\bin;C:\grid\apache-ant-1.7.0-bin\apache-ant-1.7.0\bin;

6. Click ok for all 3 windows

Way2:

In command prompt,

c:\set path=%path%;”C:\grid\apache-ant-1.7.0-bin\apache-ant-1.7.0\bin;”

3. Run the demo

Highline - Ruby Gem

July 5, 2008

HighLine is about…

Saving time.

Command line interfaces are meant to be easy. So why shouldn’t building them be easy, too? HighLine provides a solid toolset to help you get the job done cleanly so you can focus on the real task at hand, your task.

Clean and intuitive design.

Want to get a taste for how HighLine is used? Take a look at this simple example, which asks a user for a zip code, automatically does validation, and returns the result:

Code:

require “highline/import”

zipcode = ask(”Zip?  “) { |zip| zip.validate = /\A\d{5}(?:-?\d{4})?\Z/ }

Hassle-free Installation.

Installation is easy via RubyGems. Simply enter the command:

linux :   sudo gem install highline

Windows:  gem install highline

and you’ll be on your way! Of course, manual installation is an option, too.

For more details http://highline.rubyforge.org/

http://highline.rubyforge.org/svn/trunk/highline/examples/

file concept in ruby

May 6, 2008

File concept in ruby:

Ruby program
**********

full= File.open(”orig.txt”)
phrase=["phrase1","phrase2","phrase3"]
count=0
full.each do |line|
first=[]
first=line.split(/\|/)
first.each do |single|
sub=single.strip!
main = (sub).to_s + ” “+(phrase [count]).to_s
puts main
count+=1
end
end

***********************************
Orig.txt
******

item1 | item2 | item3 | item4 |
item11 | item21 | item31 | item41 |
item12 | item23 | item34 | item45 |
item13 | item23 | item33 | item43 |
item14 | item24 | item34 | item44 |
***********************************
Output
******

>ruby file.rb
item1 phrase1
item2 phrase2
item3 phrase3
item4

item11
item21
item31
item41

item12
item23
item34
item45

item13
item23
item33
item43

item14
item24
item34
item44
>Exit code: 0
*********************************

Regards,

P.Raveendran

Railsfactory.

Hi All,

Sorry for a big gap…

Command Prompt commands in Ruby:(Windows Only)

Goto Command prompt:

c:> ipconfig

It will gives the details about ur ip address.How can i get the same from Ruby code.

system(’ipconfig’)

Output:

Windows IP Configuration

Ethernet adapter Local Area Connection:

Connection-specific DNS Suffix . :

IP Address. . . . . . . . . . . . : 192.168.1.25

Subnet Mask . . . . . . . . . . . : 255.255.255.0

Default Gateway . . . . . . . . . : 192.168.1.1

Program 2:

commandprompt.rb

system(’ping 192.168.1.1′)
puts “———————”
system(’ipconfig’)

>ruby commandprompt.rb

Pinging 192.168.1.1 with 32 bytes of data:

Reply from 192.168.1.1: bytes=32 time<1ms TTL=64

Reply from 192.168.1.1: bytes=32 time<1ms TTL=64

Reply from 192.168.1.1: bytes=32 time<1ms TTL=64

Reply from 192.168.1.1: bytes=32 time<1ms TTL=64

Ping statistics for 192.168.1.1:

Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),

Approximate round trip times in milli-seconds:

Minimum = 0ms, Maximum = 0ms, Average = 0ms

———————

Windows IP Configuration

Ethernet adapter Local Area Connection:

Connection-specific DNS Suffix . :

IP Address. . . . . . . . . . . . : 192.168.1.25

Subnet Mask . . . . . . . . . . . : 255.255.255.0

Default Gateway . . . . . . . . . : 192.168.1.1

>Exit code: 0

Program3:

Shutdown,restart,logoff your windows machine using Ruby codes.

shutdown.rb

system(’shutdown.exe’)

Output:

Usage: shutdown.exe [-i | -l | -s | -r | -a] [-f] [-m \\computername] [-t xx] [-
c "comment"] [-d up:xx:yy]

No args Display this message (same as -?)
-i Display GUI interface, must be the first option
-l Log off (cannot be used with -m option)
-s Shutdown the computer
-r Shutdown and restart the computer
-a Abort a system shutdown
-m \\computername Remote computer to shutdown/restart/abort
-t xx Set timeout for shutdown to xx seconds
-c “comment” Shutdown comment (maximum of 127 characters)
-f Forces running applications to close without war
ning
-d [u][p]:xx:yy The reason code for the shutdown
u is the user code
p is a planned shutdown code
xx is the major reason code (positive integer le
ss than 256)
yy is the minor reason code (positive integer le
ss than 65536)

shutdown.rb

system(’shutdown.exe -r -f -t 0′)

Run it…

Output:

System shutdown in default.

Reference:

http://rubyonwindows.blogspot.com/

http://www.ruby-forum.com/topic/150301

Watir Cheat sheet

December 17, 2007

Watir Cheat Sheet

 

Getting Started with Watir

require ‘watir’

Load the Watir library

ie = Watir::IE.start

(’http://localhost:8080′)

Start IE using the local timeclock server.

ie.close

Close IE.

ie = Watir::IE.attach(:title, ‘title‘)

Attach to an existing IE window, so you can drive it with Watir.

 

Manipulating Controls with Watir

ie.text_field(:name, ‘name‘).set(’value‘)

Set the text field specified name specified value.

ie.button(:value, ‘value‘).click

Click the button with the specified value (label)

ie.button(:name, ‘name‘).click

Click the button with the specified name.

ie.checkbox(:name, ‘name‘).set

Check the check box named “name”. (Uncheck: clear)

ie.object(:attribute, ‘name‘).flash

Cause the specified control to flash.

 

A Special Testing Function For Timeclock

 

require ‘toolkit/testhook’

ensure_no_user_data ‘name

Delete any database records for the named user.

 

Accessing Page Contents with Watir

ie.contains_text(’text‘)

Return true if the current page has the specified text somewhere on the page. Otherwise, false.

ie.title

Return the title of the current page.

ie.html

Return all the HTML in the body of the page

ie.table(:id, ‘recent_records).to_a

Return an array containing the text in the table’s rows and columns.

ie.table(:id, ‘recent_records’)[2][1].text

Return the text from the first column of the second row of the table id’d ‘recent_records.

 

Assertions

assert_equal(expected, test_method)

Test whether the expected value matches the actual value returned by the test method

assert_match(regexp, test_method)

Test whether the regular expression matches the actual value returned by the test method.

assert(expression)

Test whether the expression is true.

Ferret in rails

December 15, 2007

View

<%= start_form_tag :action => ’search_number’ %>

<div align=”center”>
<h3>Search Phonenumber By</h3>
<table>
<tr>

<td><select name=”searchfield” prompt=”select”>
<option selected>select</option>
<option value=”phonenumber” >Phonenumber</option>
<option value=”name” >Name</option>
<option value=”city” >City</option>
</select>
</td>
<td>
<%= text_field_tag ’searchkey’ %>
<%= submit_tag “Search” %>

</tr>
</table>
</div>

<%= end_form_tag %>

Controller:

def search_number
if params[:searchfield]
session[:field]= params[:searchfield]
end
field = session[:field]

if params[:searchkey]
session[:query] = params[:searchkey]
end
query= session[:query]
@total, @phones = User.full_text_search(field,query, :page => (params[:page]||1))
@pages = pages_for(@total)
if @phones.length > 0
render :action=>’search_number’
else
render :text=>’No Result’
end

end

Profile Updation in Rails

December 15, 2007

Account Controller –>

session[:user_id]= self.current_user.id

HOME Controller inside:

def list
end

def search
@user = User.find(session[:user_id])
if @user.update_attributes (params[:user])
flash[:notice] = ‘User Name was successfully updated.’
redirect_to :action => ‘index’, :id => @user
else
redirect_to :action => ‘list’
end

end

LIST.RHTML

<%= start_form_tag :action => ’search’ %>
<%= text_field ‘user’,'name’ %>
<%= text_field ‘user’,'age’ %>
<%= submit_tag ‘Update Profile’ %>

<% end_form_tag %>

INDEX.RHTML

<%= flash[:notice] %>