Sunday, September 30, 2007

Source: http://snippets.dzone.com/posts/show/277

Create account or

DZone Snippets

8487 users tagging and storing useful source code snippets
Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
RoR Multi-step forms (See related posts)
Popular @ dzone.com




Which way you'll go in future - IronRuby, Vbx, ...

Programming Language Video Lectures

Eclipse PDT - PHP Meets Java?

Beans Binding (JSR 295)& Properties on JDK7

NetBeans IDE: Filthy Rich Client? (Part 2)

jMaki app using Google Gears

Installing Trac 0.11
Here's a controller code snippet for doing partial validations on Rails model objects:
private
def get_partial_user_from_session
unless @session['partial_user'].nil?
@user = @session['partial_user']
else
@user = User.new
end
end

def save_partial_user_in_session
unless @user.nil?
@session['partial_user'] = @user
end
end
# Might be a good addition to AR::Base
def valid_for_attributes( model, attributes )
unless model.valid?
errors = model.errors
our_errors = Array.new
errors.each { |attr,error|
if attributes.include? attr
our_errors << [attr,error]
end
}
errors.clear
our_errors.each { |attr,error| errors.add(attr,error) }
return false unless errors.empty?
end
return true
end


To ensure the errors are cleared out properly on each request add a before_filter with the following:
def clear_stage_errors
unless @session['partial_user'].nil?
@session['partial_user'].errors.clear
end
end


You can use
get_partial_user_from_session
and
save_partial_user_in_session
as before and after filters, respectively, so you only have to reference @user in your multi-step controller.

A clean way to arrange the view is to have each step in its own partial, and set a variable such as
@current_stage
in your controller, then in your view just do something like:
<%= start_form_tag({:action=> "signup"} , { :name => 'signupform' }) %>
<%= hidden_field_tag "changeCountry" %>
<%= hidden_field_tag "current_stage", "#{@current_stage}"%>

Registration Process


<%= @flash['notice'] %>

<%= render_partial "#{@current_stage}" %>
<%= end_form_tag %>


Your signup controller action could something similar to this:
def signup
case @request.method
when :post
@current_stage = @params['current_stage']
if @current_stage == "stage1"
@user.attributes = @params['user']
@current_stage = "stage2" if valid_for_attributes(@user,["login","attribute2"])
end
elsif @current_stage == "stage2"
@user.attributes = @params['user']
@current_stage = "stage3" if valid_for_attributes(@user,["attribute3","attribute4"])
elsif @current_stage == "stage3"
@user.attributes = @params['user']
if @user.save
@session[:user] = User.authenticate(@user.login, @params['user']['password'])
flash['notice'] = "Signup successful"
redirect_to :action => "home"
end
end
when :get
@current_stage = "stage1"
end
end
to ruby rails by toolmantim on Thu May 12 13:40:40 EDT 2005


You need to create an account or log in to post comments to this site.

Click here to browse all 4074 code snippets

Related Posts

» creating a select box on a table's contents in ruby rails html
» paginate on custom sql queries in rails in ruby rails pagination sql
» dynamic accessors on rails models in ruby rails
» Exceptions to layout usage in ruby rails layouts
» take tag names and return an array of tag object.. in ruby rails tags
» Pretty archive URLs in Typo with Routes in ruby rails routes typo urls


Snippets originally developed by Peter Cooper and powered by Ruby On Rails.

Copyright © 2007 DZone, Inc.

Tuesday, September 25, 2007

time.strftime( string ) => string

Format meaning:

  %a - The abbreviated weekday name (``Sun'')
%A - The full weekday name (``Sunday'')
%b - The abbreviated month name (``Jan'')
%B - The full month name (``January'')
%c - The preferred local date and time representation
%d - Day of the month (01..31)
%H - Hour of the day, 24-hour clock (00..23)
%I - Hour of the day, 12-hour clock (01..12)
%j - Day of the year (001..366)
%m - Month of the year (01..12)
%M - Minute of the hour (00..59)
%p - Meridian indicator (``AM'' or ``PM'')
%S - Second of the minute (00..60)
%U - Week number of the current year,
starting with the first Sunday as the first
day of the first week (00..53)
%W - Week number of the current year,
starting with the first Monday as the first
day of the first week (00..53)
%w - Day of the week (Sunday is 0, 0..6)
%x - Preferred representation for the date alone, no time
%X - Preferred representation for the time alone, no date
%y - Year without a century (00..99)
%Y - Year with century
%Z - Time zone name
%% - Literal ``%'' character

t = Time.now
t.strftime("Printed on %m/%d/%Y") #=> "Printed on 04/09/2003"
t.strftime("at %I:%M%p") #=> "at 08:56AM"

Thursday, September 20, 2007

Ruby Language


Source: http://www.fincher.org/tips/Languages/Ruby/

Welcome. You seem to have come here from a search engine. Your search words (ruby function) are highlighted on this page for your reading pleasure.
Ruby for the Attention Deficit Disorder Programmer - let's start learning Ruby fast!

1. Where to get Ruby

For windows you can download from http://rubyforge.org/frs/?group_id=167 for Linux try http://www.rpmfind.net (ruby comes with its own emacs mode, "ruby-mode.el").
2. Our first program

Enter the following into the file, "test.rb".

puts "Howdy!"

At the C: prompt enter,

C:>ruby test.rb

Produces:

Howdy!

OK, daylight's burning, let's move on.
3. Output in Ruby

"puts" writes to the screen with a carriage return at the end. "print" does the same thing without the carriage return. "printf" formats variables like in C and Java 5.

puts "puts works"
puts " with line breaks."

print "print works"
print " with no line breaks."

printf("\n\nprintf formats numbers like %7.2f, and
strings like %s.",3.14156,"me")

Produces:

puts works
with line breaks.
print works with no line breaks.

printf formats numbers like 3.14, and strings like
me.

4. Functions
1. Our first Ruby function

'def' starts the definition of a method, and 'end' ends it - no cute little curly braces. Parentheses are optional around the arguments we pass.

def welcome(name)
puts "howdy #{name}" # inside double quotes, #{ } will evaluate the variable
end
welcome "visitor"

This

Produces:

howdy visitor

2. How to return values from a function

we can use the faithful 'return'

def mult(a,b)
product = a * b
return product
end
puts mult(2,3)

This produces

==>6

Oddly enough you can leave out the "return" statement, and Ruby will helpfully return the last expression:

def mult(a,b)
product = a * b
end
puts mult(2,3)

or even simpler, leave out "product" and ruby returns the contents of the last expression:

def mult(a,b)
a * b
end
puts mult(3,3)

This produces

==>9

3. Optional argument values

Ruby lets you assign values to arguments which may, or may not be supplied as shown below:

def test(a=1,b=2,c=a+b)
puts "#{a},#{b},#{c}"
end
test
test 5
test 4, 6
test 3, 4, 6

This produces:

1,2,3
5,2,7
4,6,10
3,4,6

4. Extra arguments

Extra arguments are gathered into the last variable if preceded with a "*". ("each" is an iterator that loops over its members).

def test(a=1,b=2,*c)
puts "#{a},#{b}"
c.each{|x| print " #{x}, "}
end
test
test 3
test 3, 6
test 3, 6, 9, 12, 15, 18

This produces:

3,6
9, 12, 15, 18,

5. Variable naming tips:
1. Global variables start with '$'
2. Instance variables start with '@'
3. Class variables start with '@@'
4. Local variables, method names, and method parameters start with a lower case letter.
5. Class names, module names and constants start with an uppercase letter.
6. Variables names are composed of letters, numbers and underscores.
7. Method names may end with "?", "!", or "=". Methods ending with a "?" imply a boolean operation. Methods ending with "!" imply something dangerous, like strings being modified in place.
6. Interesting tidbits about Ruby,
1. '#' is the line comment character, all characters after this are ignored. Confusingly '#' can appear within quotes with a different meaning.
2. No semi-colons are needed to end lines, but may be used to separate statements on the same line
3. A backslash (\) at the end of a line is used for continuation
4. Indenting is not significant, unlike python
5. Types of variables do not need to be declared
6. Lines between =begin and =end are ignored
7. Lines following "__END__" on its own line with no white space, are ignored
8. A tiny demonstration of these:

# sample program showing special characters like comments
# I'm a comment line
a = 1 #notice no semicolon and no type declaration
b = 2; c = 3 #notice two statements on one line
name = "Abraham \
Lincoln" # a line continued by trailing \
puts "#{name}"
=begin
I'm ignored.
So am I.
=end
puts "goodbye"
__END__
1
2
3
4

Abraham Lincoln
goodbye

7. Quotes

Like in Perl, single quotes and double quotes have different meanings.

Double quotes means "please interpret special characters in this string". Things like backslash n ('\n') are converted to their typical values. The #{name} construct is converted to its value.

With single quotes, no special characters are interpreted.

Examples:

name="Mike"
puts "hi #{name}" ==>hi Mike
puts "hi\n #{name}" ==> hi (carriage return)Mike
puts 'hi\n #{name}' ==> hi\n #{name} (no substitutions are made since using single quote)

The braces are optional for global and instance variables

$myname="Ishmael"
puts "hi #$myname" ==>hi Ishmael

8. Objects

A great thing about Ruby is that numbers and strings are real objects.

1.5.floor() ==> "1"

returns the "floor" or next lower integer, "1"

parentheses in method calls are optional

"hello".upcase ==> "HELLO"

9. Collections
1. Arrays

An array of known object can be created by enclosing them in square brackets.

nums = [1, 2.0, "three"]
puts nums[2]

The above example prints "three", since Ruby arrays, like all right-thinking collections, are zero based.

You can use negative indexes to start from the end of the array

nums = [1, 2.0, "three", "four"]
puts nums[-1]

This will print "four". Using "-1" is much more concise than "nums[nums.length()-1]".

Since many arrays are composed of words and all those commas and quote marks are troublesome, Ruby provides a handy shortcut, %w:

mystuff = %w{tivo nokia ipaq} # make a string array

To get the count, or size, of an array, use the "length" method.

inspect - a convenient method to look at contents of an object. "p" is a shorthand for "puts obj.inspect"

myarray = [1,2,5,7,11]
puts myarray
puts myarray.inspect
p myarray

Produces:

1
2
5
7
11
[1, 2, 5, 7, 11]
[1, 2, 5, 7, 11]

Arrays can act like queues and sets

# & is the intersection operator
puts [1,2,3] & [3,4,5] # prints 3
# + is the addition operator
puts [1,2,3]+ [3,4,5] # prints 1,2,3,3,4,5
# - removes items from the first array that appear in the second
puts [1,2,3] - [3,4,5] # prints 1,2

# pop returns the last element and removes it from the array
alpha = ["a","b","c","d","e","f"]
puts "pop="+alpha.pop # pop=f
puts alpha.inspect # ["a", "b", "c", "d", "e"]
# push appends elements to the end of an array
alpha = ["a","b","c"]
alpha.push("x","y","z")
puts alpha.inspect # ["a", "b", "c", "x", "y", "z"]
# shift returns the first element and removes it from the array
alpha = ["a","b","c","d","e","f"]
puts "shift="+alpha.shift # shift=a
puts alpha.inspect # ["b", "c", "d", "e", "f"]
# unshift appends elements to the end of an array
alpha = ["a","b","c"]
alpha.unshift("x","y","z")
puts alpha.inspect # ["x", "y", "z", "a", "b", "c"]


2. Hashes

cars = {
'altima' => 'nissan',
'camry' => 'toyota',
'rx7' => 'mazda'
}
puts cars['rx7']

produces

mazda

You can also create Hashes with square brackets:

toppings = Hash["pancakes","syrup","Pizza","Pepper","Cereal","Sugar"]
puts toppings.inspect

Produces:

{"Pizza"=>"Pepper", "Cereal"=>"Sugar", "pancakes"=>"syrup"}

The "each" method is a wonderful way to iterate over the keys

toppings = Hash["pancakes","syrup","Pizza","Pepper","Cereal","Sugar"]
toppings.each{|key, value| puts "#{key} points to #{value}"}

Produces:

Pizza points to Pepper
Cereal points to Sugar
pancakes points to syrup

The "select" method populates a new array with members which meet a criteria

salaries = Hash["bob",10.9,"larry",7.5,"jimmy",6.0,"jerry",6.5]
salaries.inspect
mySalaryArray = salaries.select{|name,salary| salary > 7.0}
puts mySalaryArray.inspect

Produces:

[["larry", 7.5], ["bob", 10.9]]

3. Ranges

Ranges are composed of expr..expr or expr...expr. Two dots includes the last element, three dots excludes it.

('a'..'g').each{ |letter| puts letter }

Produces:

a
b
c
d
e
f
g

(1...3).each{ |num| puts num }

Produces:

1
2

10. Control Statements
1. if

income = 30000.00
if income < rate =" 0.02" rate =" 0.28" rate =" 0.5" grade =" 10" school =" case" top =" 6" lines =" IO.readlines(" i="0"> 5
puts i
i += 1
end

11. Statement modifiers

These are syntatic sugar

balance = -10.0
puts "Bankrupt" if balance < balance =" -10.0"> 0.0

f=2
puts f=f+2 while f < 10 ="=">4
==>6
==>8
==>10

12. Iterators
1. while

i = 0
while i < i =" i+1" n =" 10" animals =" %w(lions" n="0" max="7" fname =" fname" lname =" lname" person =" Person.new(">

which is true, but not helpful.
2. The "ToString" method, to_s

class Person
def initialize(fname, lname)
@fname = fname
@lname = lname
end
def to_s
"Person: #@fname #@lname"
end
end
person = Person.new("Augustus","Bondi")
print person

Produces:

Person: Augustus Bondi

3. Subclassing

In Ruby subclassing is done with the "<" character class Employee < position =" position" employee =" Employee.new(" position =" position" employee =" Employee.new(" position = "CEO" position =" position" position ="=" position ="=" employee =" Employee.new(" position = "CEO" position = "Engineer" i="0" lastname = "Croton" firstname = "Milo" rate =" 0.15" mytip =" tip(10.0)" file =" File.new(" mytext =" file.read" lines =" IO.readlines(" file =" File.open(" line =" file.gets" file =" File.open(" line =" file.gets" file =" File.new(" bytes =" file.readbytes(80)" file =" File.new(" bytes =" file.readbytes(80)" mathwiz =" MathWiz.new" file =" File.new(" doc =" REXML::Document.new" class="'entry']">ruby -e 'sleep 2'
c:\home\mfincher>ruby -e 'puts 3*4'
12
c:\home\mfincher>ruby -e 'puts 3*4; puts 4*4'
12
16

26. Editing files in place

Ruby offers a simple way to make a string substitution in many files all at once with a single line of code. The "-p" option loops over the files, the "-i" is the backup extension. With this command we are changing all the documentation from version 1.5 to 1.6, but the original files are renamed to ".bak".

C:\home\mfincher\ruby>more v2.txt
Regarding version 1.5 ...
....
version 1.5 is easy to install

C:\home\mfincher\ruby>ruby -pi.bak -e "gsub(/1.5/,'1.6')" v*.txt

C:\home\mfincher\ruby>more v2.txt
Regarding version 1.6 ...
....
version 1.6 is easy to install

C:\home\mfincher\ruby>more v2.txt.bak
Regarding version 1.5 ...
....
version 1.5 is easy to install

27. Example of printing duplicate lines in sorted file.

#prints duplicate lines in sorted files in the file passed in as first arg
file = File.open(ARGV[0])
lastLine = ""
counter = 0
while line = file.gets
counter += 1
if lastLine == line
puts "#{counter-1}: #{line}#{counter}: #{line}\r\n"
end
lastLine = line
end
puts "done. Processed #{counter} lines"

28. Ruby has its own interpreted shell, irb.

C:\home\mfincher>irb
irb(main):001:0> puts "Hello World"
Hello World
=> nil
irb(main):002:0> a=1
=> 1
irb(main):003:0> a*2
=> 2
irb(main):004:0>

29. ruby can take input from stdin

echo 'puts "hello"' | ruby

30. to pass a string on the url it needs to be "escape"'d first.

require 'uri'
...
URI.escape("some string...")

31. Example to remove "funny" characters from a filename

Example of iterating over the filenames in a directory, using regular expression substitution in strings, and renaming files.

#replaces any "funny" characters in a filename in the current directory with an underscore
#if the new file name already exists, this skips it.
Dir.foreach(".") { |f|
print "testing \"#{f}\""
if f =~ /[^\w\-\.]/ #filename contains something other than letters, numbers, _,-, or .
puts "\r\n name with funny characters: #{f}"
newName = f.gsub(/[^\w\.\-]/,"_") # \w is any word character, letter,num or _
if File.exist?(newName)
puts " File #{newName} already exists. Not renaming."
else
puts " renaming #{f} to #{newName}"
File.rename(f,newName)
end
else
puts " it's ok."
end
}


32. Looping over list of arguments

ARGV.each {|f|
puts f
counter = 0
file = File.open(f,"r")
ftmp = f+".tmp"
tmp = File.open(ftmp,"w")
while line = file.gets
if line =~ /pid="2"/
counter += 1
line = line.gsub(/pid="2"/,"pid=\"#{f}:#{counter}\"")
puts line
end
tmp.print line
end
file.close
tmp.close
puts "renaming #{ftmp} to #{f}"
File.rename(ftmp,f)
}


33. Miscellanous Commands
command description example result
global_variables returns all global variables
local_variables returns all local variables
sleep seconds sleeps specified seconds
rand returns a random number between 0 and 1
rand(max) returns int between 0 and max
warn like print, but writes to STDERR


Interesting string functions
command description example result
center centers string "City".center(20) "________City________"
ljust left justifies "State".ljust(30) "State_________________________"
rjust right justifies "State".rjust(30) "_________________________State"
gsub global regex replacesments "this is a test".gsub(/[aeiou]/,'_\1') th_s _s _ t_st
tr translates "The greatest of these is".tr('aeiou','*') Th* gr**t*st *f th*s* *s
each splits and iterates "one:two:three".each(':'){|x| puts x}
one:
two:
three
34. DateTime

puts DateTime.now #prints 2006-11-25T14:26:15-0600
puts Date.today #prints 2006-11-25
puts Time.now #prints Sat Nov 25 14:29:57 Central Standard Time 2006

35. Introspection with ObjectSpace

You can find all the objects in your program of a particular type using ObjectSpace.each_object.

class Person
def initialize(name,age)
@name = name
@age = age
end
attr_reader :name
end
p = Person.new("Alfred",34)
p2 = Person.new("Janie",31)
ObjectSpace.each_object(Person) {|s|
puts s.name
}

Produces:

Janie
Alfred

36. Testing

Ruby comes right out of the box with a testing framework. Here's a quick example:

require 'test/unit'

class TestMe < s =" 1" canvas2 =" TkCanvas.new(root)"> 'top', 'fill'=>'both', 'expand'=>'yes')
points = []
end
TkcLine.new(canvas2, 0,0,100,100)
end
Tk.mainloop

39. irb - interactive ruby

Ruby comes with an REPL (Read Eval Print Loop) utility to let you try ruby interactively. ("inf-ruby.el" provides an internal shell in emacs for irb).

C:>irb
irb(main):001:0> puts "hello"
puts "hello"
hello
nil
irb(main):002:0> Object.methods
Object.methods
["send", "name", "class_eval", "object_id", "new", "singleton_methods", "__send__", "private_method_defined?", "equal?", "taint", "frozen?", "instance_variable_get", "constants", "kind_of?", "to_a", "instance_eval", "require", "ancestors", "const_missing", "type", "instance_methods", "protected_methods", "extend", "protected_method_defined?", "eql?", "public_class_method", "const_get", "instance_variable_set", "hash", "is_a?", "autoload", "to_s", "class_variables", "class", "tainted?", "private_methods", "public_instance_methods", "instance_method", "untaint", "included_modules", "private_class_method", "const_set", "id", "<", "inspect", "<=>", "==", "method_defined?", ">", "===", "clone", "public_methods", "protected_instance_methods", "require_gem", ">=", "respond_to?", "display", "freeze", "<=", "module_eval", "autoload?", "allocate", "__id__", "=~", "methods", "gem", "method", "public_method_defined?", "superclass", "nil?", "dup", "private_instance_methods", "instance_variables", "include?", "const_defined?", "instance_of?"] irb(main):003:0>

40. RubyGems a ruby package installer

You can download RubyGems from http://rubyforge.org. Unzip the files (eg, C:\opt\ruby) then install by entering:

C:>cd C:\opt\ruby\rubygems-0.9.0
C:\opt\ruby\rubygems-0.9.0>ruby setup.rb all

41. Ruby on Rails
1. How to write a log message

You can use logger's methods "warn", "info", "error", and "fatal".

logger.info("request.remote_ip"+request.remote_ip);

2. Field names ending with "_at" are assumed to be datetime fields and are filled in automagically by rails for ActiveRecord objects. The suffix "_on" are assumed to be dates.
3. Console

to dubug applications it's convenient to use the console script

myapp>ruby script/console

4. debug method

You can use the debug() method inside web pages to dump info about an object.

Thanks for visiting


<%= debug(@myobject) %>

5. Active record notes
1.

Find all records meeting a criteria

def self.suitable_jokes(sort_key)
if sort_key == "Newest"
find(:all,
:conditions => "suitable = \"1\"",
:order => "entry_date DESC"
)
elsif sort_key == "Worst"
find(:all,
:conditions => "suitable = \"1\"",
:order => "entry_date ASC"
)
else
find(:all,
:conditions => "suitable = \"1\"",
:order => "current_rating DESC"
)
end
end

The first argument to find can also be ":first" or ":last".
2. Find the count of records meeting a criteria

def self.waiting_jokes()
count("suitable = \"0\"")
end
def self.total()
count("suitable = \"1\"")
end

Find the total number of items

count = Joke.count

Find the total number of items meeting a criteria

count = Joke.count(["suitable = \"1\""])

3. Pagination

The ":limit" and ":offset" options allow easy pagination.

To return the fifth page of items use the following:

find(:all,
:conditions => "suitable = \"1\"",
:order => "current_rating DESC",
:limit => 10,
:offset => 40
)

4. Use raw SQL and return two values

def getAverageRatingAndCount
record = Rating.find_by_sql(["select count(*) as count,avg(rating) as average from ratings WHERE joke_id = ?",id]);
return record[0].average.to_f , record[0].count.to_i
end

5. The "create" method in ActiveRecord will do "new" and "save" operations simultanously.

mydog = Dog.create(
:name => "Fido"
:breed => "Collie"
)

42. Ruby Quotes:


"Ruby is a language for clever people." -Matz
"Ruby is the perlification of Lisp." -Matz
"Java is a pair of scissors, Ruby is a chainsaw." -Mitch Fincher
"Type Declarations are the Maginot line of programming." -Mitch Fincher


Wednesday, September 12, 2007

Could not find rails (> 0) in any repository

Source : http://armyofevilrobots.com/node/418

ACK!

The problem is solved by following the instructions here: Delete Your RubyGems Cache. Here is the secret sauce:

gem env
#which will give you something like this:
RubyGems Environment:
- VERSION: 0.9.2 (0.9.2)
- INSTALLATION DIRECTORY: /usr/lib/ruby/gems/1.8
- GEM PATH:
- /usr/lib/ruby/gems/1.8
- REMOTE SOURCES:
- http://gems.rubyforge.org

Next you type the following:

rm -f /PATH/TO/GEM/PATH/FROM/ABOVE/source_cache

Sadly, this was not sufficient for me :(

If you still find that you are getting the Could not find rails (> 0) in any repository error, or the even more insidious:Could not find rubygems-update (> 0) in any repository then you may need to repeat the instructions posted above, then:

gem update --system #for gems 0.8.X or lower
gem update #for 0.9.0 or newer. This is not documented ANYWHERE.

Nearly done! Now you can probably successfully type:

gem install rails

Note that the syntax for the gem update seems to have changed since 0.8.11, and requires you to run without the --system switch. Why this is (and why the --system switch is still listed in the gem help update docs) I have no idea. Good luck!