begin
somecode()
rescue
puts "Error #{$!}"
ensure
this_code_will_execute_always()
end
From the rails on ruby warrior:
http://railswarrior.blogspot.com/2008/10/ruby-on-rails-try-catch-finally...
Okay, so I am about to try another test application on rails again. The tutorial break when rails moved from 1.x to 2.x was a big turn off for me; I couldn't find one piece of documentation that would easily show me how to create a rails app. Also, there was that pesky many to many issue.
But that was years ago. Now I am going to try it again and see how it goes. :)
This was the only code that I found where it made it easy to execute a query to a MS SQL Server db. If you are running it on windows, the libary, win32ole, comes with the installation. It is a small class that handles the connection and execution of the db.
I normally copy interesting code here and give the link, but the post is so short and to the point that I will just thank David Mullet, for this great piece of code. It made my day :)
http://rubyonwindows.blogspot.com/2007/03/ruby-ado-and-sqlserver.html
I changed my mind. Here is the text of the post:
Ruby, ADO, and SQLServer
Ruby and ActiveX Data Objects (ADO) make working with Microsoft SQL Server databases simple. Here's a simple example of a class that manages the SQL Server database connection and queries:
require 'win32ole'
class SqlServer
# This class manages database connection and queries
attr_accessor :connection, :data, :fieldsdef initialize
@connection = nil
@data = nil
enddef open
# Open ADO connection to the SQL Server database
connection_string = "Provider=SQLOLEDB.1;"
connection_string << "Persist Security Info=False;"
connection_string << "User ID=USER_ID;"
connection_string << "password=PASSWORD;"
connection_string << "Initial Catalog=DATABASE;"
connection_string << "Data Source=IP_ADDRESS;"
connection_string << "Network Library=dbmssocn"
@connection = WIN32OLE.new('ADODB.Connection')
@connection.Open(connection_string)
end>>>>>>def query(sql)
# Create an instance of an ADO Recordset
recordset = WIN32OLE.new('ADODB.Recordset')
# Open the recordset, using an SQL statement and the
# existing ADO connection
recordset.Open(sql, @connection)
# Create and populate an array of field names
@fields = []
recordset.Fields.each do |field|
@fields << field.Name
end
begin
# Move to the first record/row, if any exist
recordset.MoveFirst
# Grab all records
@data = recordset.GetRows
rescue
@data = []
end
recordset.Close
# An ADO Recordset's GetRows method returns an array
# of columns, so we'll use the transpose method to
# convert it to an array of rows
@data = @data.transpose
end>def close
@connection.Close
end
endYou can then use this class as follows:
db = SqlServer.new
db.open
db.query("SELECT PLAYER FROM PLAYERS WHERE TEAM = 'REDS';")
field_names = db.fields
players = db.data
db.closeThe above code is, of course, incomplete and can certainly be improved and extended (error handling, etc.). But, hopefully, it provides you with a solid foundation on which to build.
UPDATE: You might like to know that you can automate many of your SQL Server administrative tasks by leveraging Distributed Management Objects (SQL-DMO). I've explained this in a later article here.
Thanks for stopping by!
Summary:
Only use >>unless<< in statement modifiers and without else.
The long story:
I went last week to Ruby Nation, and during one talk, the speaker made a big point on how one should try to learn idiomatic ruby. Then he went through a number of examples on what idioms one should be using. That was a great talk for me, and I am already trying to apply the principles that he gave, such as method_names_with_underscore, using attr_accessor (which are awesome) and using hashes for configuration files.
basedir = "."
contains = Dir.new(basedir).entries
puts contains
Source:
http://www.wellho.net/resources/ex.php4?item=r106/afid.rb
This was the winning code:
path="/some/path"
if File.exists?(path) && File.directory?(path)
puts "yeeha"
else
puts "bummer"
end
from this source http://www.ruby-forum.com/topic/135748
The author wanted to find the right way of doing this in ruby. I just wanted it to work, so this is good enough. Thanks, Mark Needham!
require 'rubygems'
require 'zip/zip'
def unzip_file (file, destination)
Zip::ZipFile.open(file) { |zip_file|
zip_file.each { |f|
f_path=File.join(destination, f.name)
FileUtils.mkdir_p(File.dirname(f_path))
zip_file.extract(f, f_path) unless File.exist?(f_path)
}
}
end
http://www.markhneedham.com/blog/2008/10/02/ruby-unzipping-a-file-using-...
How to download zip files with ruby
Here is the example that gave me the solution:
require 'net/http'
Net::HTTP.start("static.flickr.com") { |http|
resp = http.get("/92/218926700_ecedc5fef7_o.jpg")
open("fun.jpg", "wb") { |file|
file.write(resp.body)
}
}
puts "Yay!!"
http://snippets.dzone.com/posts/show/2469
Thanks!
Here is my adaptation since I was using httpclient
stream = client.get_content(zipURL)
file = open("test", "wb")
file.write(stream)
file.close
This one takes a csv file and breaks it into files with 100K records, adding the header on each one of them.
#!/usr/bin/env ruby
fileString = ARGV[0]
if ARGV[1]
outputDirectory = ARGV[1]
else
outputDirectory = "output"
end
if !(File.directory? outputDirectory) then
Dir.mkdir(outputDirectory)
end
fileName = fileString.match(/(^.*)\./)[1]
extension = fileString.match(/\.(.*$)/)[1]
data = File.open(fileString)
header = data.readline
i = 1
fileIndex = 1
limit = 100000
output = nil
data.each { |line|
if i >= limit then
if defined? output then
Inspired by Darwin twittering, I got an account for Francisco I. Madero, initial leader of the Mexican Revolution of 1910. Write now I have him twittering random quotes from his book, The Presidential Succession. This is topical since the 100 anniversary of the Mexican Revolution is about to hit the next year. I got to make some changes to the script so that it will hash out certain key terms. Madero is exclusively twittering in Spanish :P
The code is below:
require 'grackle'
file = IO.readlines("maderobook.txt")
randomLine = rand(file.length) + 1