Showing posts with label Ruby. Show all posts
Showing posts with label Ruby. Show all posts

Thursday, March 20, 2008

Playing with Signals in Ruby

What?

Signal trapping and processing in Ruby - it's way easy.

Why?

Signals are very useful, e.g. to detect shutdown and let your program clean up after itself.

How?

Here's a quickie that'll get you started playing.



# Let's see which signals we can trap

{
"ABRT"=>6, "ALRM"=>14, "BUS"=>7,
"CHLD"=>17, "CLD"=>17, "CONT"=>18,
"FPE"=>8, "HUP"=>1, "ILL"=>4,
"INT"=>2, "IO"=>29, "IOT"=>6,
"KILL"=>9, "PIPE"=>13, "PROF"=>27,
"QUIT"=>3, "SEGV"=>11, "STOP"=>19,
"SYS"=>31, "TERM"=>15, "TRAP"=>5,
"TSTP"=>20, "TTIN"=>21, "TTOU"=>22,
"URG"=>23, "USR1"=>10, "USR2"=>12,
"WINCH"=>28, "XCPU"=>24, "XFSZ"=>25
}.each do |signal,num|
puts "Set up trap for #{signal} #{num}"
trap signal do
puts "#{signal} #{num} was trapped"
end
end

# Sleep away and lets press some buttons. Try for example ctr-c
sleep 100


Also check out:


at_exit do
puts "I'm quitting now!"
end


Very useful!

Friday, March 14, 2008

Publish Ruby gems to RubyForge in 10 minutes

What?

A quick tutorial to how to publish your ruby gems to the rubyforge gem listing in just under 10 minutes.

This is a fat-reduced version of nuby on rails' tutorial. Thanks for the great info!

Why?

You want to share your code, right? Sharing your ruby code is *really easy*!

How?

Using hoe. This assumes you already have a rubyforge account and a project approved. See https://rubyforge.org/account/register.php to set up an account and http://rubyforge.org/register/projectinfo.php to register a project.

Setup


sudo gem install hoe --include-dependencies

Set your environment EDITOR variable, if you haven't already. Edit ~/.profile or ~/.bash_login or equivelant, and put in

# ~/.bash_login
export EDITOR=/usr/bin/mate -w

Set up your computer to be able to talk to rubyforge. This will open a configuration file in your editor. Change the username and email

rubyforge setup
Log in to rubyforge

rubyforge login
Sow your project

For a project registered with rubygorge as object-stash you would do:

sow object-stash

This creates a directory object-stash with the files:

History.txt
Manifest.txt
Rakefile
README.txt
bin
sparklines
lib
sparklines.rb
test
test_sparklines.rb

It will list in the command line what you need to fix in the auto generated files.

*Note* If your project name contains a dash - you will have to fix the the class name from "Object-stash" to ObjectStash in lib/object-stash.rb and Rakefile. A shortcoming of hoe, but a minor one.

If you want to auto-publish your documentation to the project main site, e.g. http://object-stash.rubyforge.org/, then edit Rakefile and add:


p.remote_rdoc_dir = '' # Release to root

Write your code

Add and edit files in lib

Release

Run


rake check_manifest


to make sure your Manifest file is correct. The lines with a - are listed in the Manifest but don’t exist on disk. The lines with a + are not in the Manifest but are on the disk.

*Note* Make sure the file ends with at least one blank line!

Now edit History.txt

== 1.0.1

* New version
* Features


Update the version number in your ruby class files:

# lib/object-stash.rb
class ObjectStash
VERSION = '1.0.1'
end
Release!


rake release VERSION=1.0.1

Publish your docs!

rake publish_docs

View docs and install your gem remotely

Go to your project's base url to view the docs, e.g. http://object-stash.rubyforge.org/.

Install your own gem! As easy as 1, 2,

sudo gem install object-stash

Save Ruby objects to disk for later reload

What?

A way to store entire Ruby objects to disk.

Why?

Let's say you have a data structure that takes a long time to build, e.g. dictionary trie for the English language.

It wold be nice to be able to compute this data structure only once, then store it in some way for later retrieval.

How?

Using Ruby's standard library Marshal class, we can easily serialize an object and write it to disk. Combined with the gzip library we even have efficient storage.

Here's the result:


require 'zlib'

# Save any ruby object to disk!
# Objects are stored as gzipped marshal dumps.
#
# Example
#
# # First ruby process
# hash = {1 => "Entry1", 2 => "Entry2"}
# ObjectStash.sotre hash, 'hash.stash'
#
# ...
#
# # Another ruby process - same_hash will be identical to the original hash
# same_hash = ObjectStash.load 'hash.stash'
class ObjectStash

# Store an object as a gzipped file to disk
#
# Example
#
# hash = {1 => "Entry1", 2 => "Entry2"}
# ObjectStore.store hash, 'hash.stash.gz'
# ObjectStore.store hash, 'hash.stash', :gzip => false
def self.store obj, file_name, options={}
marshal_dump = Marshal.dump(obj)
file = File.new(file_name,'w')
file = Zlib::GzipWriter.new(file) unless options[:gzip] == false
file.write marshal_dump
file.close
return obj
end

# Read a marshal dump from file and load it as an object
#
# Example
#
# hash = ObjectStore.get 'hash.dump.gz'
# hash_no_gzip = ObjectStore.get 'hash.dump.gz'
def self.load file_name
begin
file = Zlib::GzipReader.open(file_name)
rescue Zlib::GzipFile::Error
file = File.open(file_name, 'r')
ensure
obj = Marshal.load file.read
file.close
return obj
end
end
end

if $0 == __FILE__
require 'test/unit'
class TestObjectStash < Test::Unit::TestCase
@@tmp = '/tmp/TestObjectStash.stash'
def test_hash_store_load
hash1 = {:test=>'test'}
ObjectStash.store hash1, @@tmp
hash2 = ObjectStash.load @@tmp
assert hash1 == hash2
end
def test_hash_store_load_no_gzip
hash1 = {:test=>'test'}
ObjectStash.store hash1, @@tmp, :gzip => false
hash2 = ObjectStash.load @@tmp
assert hash1 == hash2
end
def test_self_stash
ObjectStash.store ObjectStash, @@tmp
assert ObjectStash == ObjectStash.load(@@tmp)
end
def test_self_stash_no_gzip
ObjectStash.store ObjectStash, @@tmp, :gzip => false
assert ObjectStash == ObjectStash.load(@@tmp)
end
end
end




Here's an example:

# Here's our theory of everything - make it heavy
theory_of_everything = { :question => "Life, Universe & Everything", :answer => 42 }
1000.times {|i| theory_of_everything[i] = "rubbish#{i}" }

# Stash it
ObjectStash.store theory_of_everything, './theory_of_everything.stash'

# Let's see what it did
File.stat('./theory_of_everything.stash').size # => 4206

# Reload it
loaded_theory_of_everything = ObjectStash.load 'theory_of_everything.stash'
question = loaded_theory_of_everything[:question]
answer = loaded_theory_of_everything[:answer]
puts "The answer to #{question} is #{answer}" # => The answer to Life, Universe & Everything is 42


And for the curious - I wrote up a series of tests to make sure I grok how/that this works as I expect it to:


def report msg
puts msg
t=Time.now
yield
puts " -> #{Time.now-t}s"
end

def test_hash_equality hash1, hash2
throw :HashesNotEqual unless hash1 == hash2
throw :HashesNotTreeEqual unless hash1 === hash2
hash1.each do |key,value|
throw :HashCopyDoesNotHaveKey unless hash2.has_key? key
throw :HashCopyDoesNotHaveValue unless hash2.has_value? value
end
end

original_hash = Hash.new
loaded_hash = nil
marshal_dump = nil

report "Build a big hash to be marshalled" do
(0..1000).each do |i|
original_hash[i] = "Entry #{i}"
end
end

report "Store the hash" do
marshal_dump = Marshal.dump(original_hash)
end

report "Load a hash from the dump" do
loaded_hash = Marshal.load(marshal_dump)
end

report "Assert hashes are equal" do
test_hash_equality original_hash, loaded_hash
end

report "Write the marshal dump to file" do
file_out = File.new("marshal_test.tmp",'w')
file_out.write(marshal_dump)
file_out.close
end

report "Construct hash from the marshal file dump" do
file_in = File.new('marshal_test.tmp','r')
loaded_hash = Marshal.load(file_in.read)
file_in.close
end

report "Assert hashes are equal" do
test_hash_equality original_hash, loaded_hash
end

require 'zlib'
report "Gzip the marshaled dump" do
file = File.new('marshal_test.tmp.gz','w')
gz = Zlib::GzipWriter.new(file)
gz.write marshal_dump
gz.close
end

report "Gunzip the marshaled dump and load it" do
gz = Zlib::GzipReader.open('marshal_test.tmp.gz')
loaded_hash = Marshal.load gz.read
gz.close
end

report "Assert hashes are equal" do
test_hash_equality original_hash, loaded_hash
end

puts "Success!"

Tuesday, March 4, 2008

Html-R: Make our Ruby HTML Pretty

What?

Html-R, an ajaxified online Ruby2HTML converter.

Why?

When you share your code online, it should look good and be readable, just like in your favorite text editor (emacs, right?).

With TextMate inspired syntax highlighting, Html-R quickly turns this



# Why's (Poignant) Guide to Ruby - The Endertrombe Wishmaker
require 'endertromb'
class WishMaker
def initialize
@energy = rand( 6 )
end
def grant( wish )
if wish.length > 10 or wish.include? ' '
raise ArgumentError, "Bad wish."
end
if @energy.zero?
raise Exception, "No energy left."
end
@energy -= 1
Endertromb::make( wish )
end
end
into that

# Why's (Poignant) Guide to Ruby - The Endertrombe Wishmaker
require 'endertromb'
class WishMaker
def initialize
@energy = rand( 6 )
end
def grant( wish )
if wish.length &gt; 10 or wish.include? ' '
raise ArgumentError, "Bad wish."
end
if @energy.zero?
raise Exception, "No energy left."
end
@energy -= 1
Endertromb::make( wish )
end
end

How?

Using jQuery, there's a listener that sits and waits for changes to the source code. After new code appears, it sends a re quest to the server which uses the syntax gem to generate the appropriate html.

The appended css is of my own design, and is intended to mimic that of TextMate.

Here are screenshots of the step by step process. Or you can just demo it yourself.




Thursday, February 14, 2008

Ruby acts_as_taggable plugin bug fix for Rails 2.0.2

What?
I'm working on a small rails app and wanted tags, so I went ahead and installed the acts_as_taggable plugin. However, I had some problem with installation. First, I just ran

./script/plugin install acts_as_taggable

and followed setup procedures. However, I then got the following error when I called acts_as_taggable in my class

NameError: uninitialized constant Tag

I then found a post that directed me to the correct source for the tag:

./script/plugin install http://svn.rubyonrails.org/rails/plugins/legacy/acts_as_taggable/

However, running rails 2.0.2, the has_many API has changed, so I got the following error:

ArgumentError (The :dependent option expects either :destroy, :delete_all, or :nullify (true))

I traced the error down in the plugin to the file rails_root/vendor/plugins/acts_as_taggable/lib/acts_as_taggable.rb

The error is on line 18

has_many :taggings, :as => :taggable, :dependent => true

should be

has_many :taggings, :as => :taggable, :dependent => :destroy

Now it works!

Wednesday, February 13, 2008

Ruby: All Combinations / Permutations up to length n-1 of a String

What?
In writing a Scrabble like game, I needed a quick fix to get all possible combinations of a string (of length 1..n). I would then look these combinations up in the dictionary to determine if they are words valid for placement.

Why?
It would be nice to able to do the following:

'abc'.combinations.each do |combo|
dictionary.lookup(combo)
end
So I hacked up the following:
class String
# Get all the combinations of a string.
# Returns an array of all combinations of a string
# If a block is given, then that block is called once for each combination
def combinations &action
ret = []
0.upto length-1 do |n|
#rest = self.split('') # regular
rest = self.split(//u) # UTF-8
picked = rest.delete_at n
action.call picked if action
ret << picked
rest.join.combinations.each do |perm|
genperm = picked+perm
ret << genperm
action.call genperm if action
end
end
ret
end
end
Which does the following:
p 'abc'.combinations # => ["a", "ab", "abc", "ac", "acb", "b", "ba", "bac", "bc", "bca", "c", "ca", "cab", "cb", "cba"]

'abc'.combinations do |combination|
puts combination
end
# =>
# a
# ab
# abc
# ac
# acb
# b
# ba
# bac
# bc
# bca
# c
# ca
# cab
# cb
# cba
Just what I wanted!


Sunday, February 10, 2008

Sequential Contracts in Ruby - Design by Contract Extension


What?

Software Designed By Contract is constructed along with terms of use and guaranteed behavior.

There are (at least) three types of contracts:
  • Pre-conditional contracts specify conditions that have to be met before a function is used, e.g. the demand that a value passed into a function is greater than or equal to 0
  • Post-conditional contracts specify conditions that are guaranteed to be be fulfilled after a functionality is used, e.g. ruby's Array#flatten! method guarantees that the resulting array is either nil or one-dimensional.
  • Sequence contracts specify the sequence in which functionalities are allowed to be used. For example, a File class could specify the sequence File#open, multiple File#read's, File#close.
Why?

While documenting expected conditions gives the user of a software component an indicator what and what not to do, this cannot guarantee that conditions are actually met and can result in unexpected errors. Thus, we want a method to formally define contracts and ensure that they are met at run-time.

Ruby does not have built in support for contracts, but Ruby programmers Martin and Brian created a neat module for pre- and post-conditional contracts. However, it does not support sequential contracts. I recently had the need for sequential contracts in Ruby, and so decided to go ahead and implement it.

How?

To declare a sequential contract for a class, you first define the methods and then declare the sequence in which you expect the methods of any given object to be called. Let's say we have a Greeter class that creates conversing objects:

class Greeter

def greet
puts "Hello!"
end

def ignore
puts "Pss!"
end

def ask_question
puts "How are you?"
end

def talk
puts "Blah blah blah"
end

def give_answer
puts "Good thank you!"
end

def say_goodbye
puts "Bye!"
end

def leave
puts "Walking away..."
end
end


Obviously, we would not want our greeter to first greet and then ignore you, or leave before it says goodbye. So let's declare a sequence contract after the methods of the Greeter class:

g = Greeter.new
g.greet

g.ask_question
# Must say goodbye before you leave!
g.leave


Now, if we create a Greeter and have it behave in a bad manner (e.g. ask a question without saying hello, or leaving before saying goodbye), then an IllegalSequence exception is raised:


# Declare a sequential contract
extend SequenceContract
sequence_contract do
start do
transition 'greet' => :chat
transition 'ignore' => :walk_away
end
state :chat do
transition 'ask_question' => :chat
transition 'talk' => :chat
transition 'give_answer' => :chat
transition 'say_goodbye' => :walk_away
end
state :walk_away do
transition 'leave' => :done
end
end
Together with test cases, the whole baddabing looks like:

require 'test/unit'
class TestSequenceContract < Test::Unit::TestCase

class Greeter
# Declare a sequential contract
include SequenceContract

def greet
puts "Hello!"
end

def ignore
puts "Pss!"
end

def ask_question
puts "How are you?"
end

def talk
puts "Blah blah blah"
end

def give_answer
puts "Good thank you!"
end

def say_goodbye
puts "Bye!"
end

def leave
puts "Walking away..."
end

sequence_contract do
start do
transition 'greet' => :chat
transition 'ignore' => :walk_away
end
state :chat do
transition 'ask_question' => :chat
transition 'talk' => :chat
transition 'give_answer' => :chat
transition 'say_goodbye' => :walk_away
end
state :walk_away do
transition 'leave' => :done
end
end
end

def test_illegal_sequence
g = Greeter.new
assert_nothing_raised do
g.greet
g.ask_question
end
assert_raises SequenceContract::IllegalSequence do
g.leave
end
end

def test_legal_sequence
assert_nothing_raised do
g = Greeter.new
g.greet
g.ask_question
g.say_goodbye
g.leave
end
end

def test_multiple_instances
g = Greeter.new
assert_nothing_raised do
g.greet
g.ask_question
g.say_goodbye
end
g = Greeter.new
assert_raises SequenceContract::IllegalSequence do
g.leave
end
assert_nothing_raised do
g.greet
g.ask_question
g.say_goodbye
g.leave
end
end
end # TestSequenceContract

The SequenceContract module itself can be found here for now.