Code Snippet: Ruby Walks with Shoes

Posted by Ryan Baxter Tue, 30 Oct 2007 14:30:00 GMT

_Why of Why’s (Poignant) Guide to Ruby has announced the publication of a 52 page comic style book illustrating the ins and outs of his new windowing toolkit, Shoes. In his words, “Shoes is a very informal graphics and windowing toolkit. It’s for making regular old apps that run on Windows, Mac OS X and Linux. It’s a blend of my favorite things from the Web, some Ruby style, and a sprinkling of cross-platform widgets.”

Using the the latest Shoes revision, I’ve written some code to generate a Mandelbrot fractal. Try it out with the following command (assuming your script is located in the Shoes samples directory):

./shoes samples/mandelbrot.rb

You may want to go make a sandwich while you wait. Here is a sample of the output:

Here is the code:

# RB

require 'complex'

class Mandelbrot  
  def initialize(bailout=10, iterations=100)
    @bailout, @iterations = bailout, iterations   
  end  

  # A method for determining if a point is within
  # the Mandelbrot set.
  def in_set?(x, y)
    c = Complex(x, y)
    z = 0
    @iterations.times do |i|
      z = z**2 + c                       
      return false if z > @bailout
    end
    return true 
  end  
end

class Generator < Shoes
  url '/', :index

  def index()    
    render(250, 250, rgb(205, 102, 0))    
  end

  def render(height=250, width=250, color=rgb(255, 0, 0))
    nostroke
    fill color   

    mandelbrot = Mandelbrot.new

    # Render the fractal.
    0.upto(height) do |y|
      0.upto(width) do |x|
        scaled_x = -2 + (3 * x / width.to_f)
        scaled_y = 1 + (-2 * y / height.to_f)
        if mandelbrot.in_set?(scaled_x, scaled_y) then        
          rect :left => x, :top => y, :width => 1, :height => 1
          # oval :left => x, :top => y, :radius => 1, :center => true                           
        end      
      end
    end
  end
end

Shoes.app :title => 'Mandelbrot', :height => 250, :width => 250

Code Snippet: Ruby Image Scraper

Posted by Ryan Baxter Tue, 14 Aug 2007 03:46:00 GMT

I stumbled upon a screen scraping library for Ruby last week called scrAPI. It’s extremely flexible and can be seen in action on the co.mments blog post scraper. The scrAPI library can be installed by issuing the following command from your console:

gem install scrapi

Testing scrAPI was fairly easy once I figured out how to define a scraper. With that aside, I wrote a small script that saves images from a URL provided by the user. The scrAPI library could be used for good or evil, but only you can decide.

#!/usr/bin/ruby

require 'fileutils'
require 'open-uri'
require 'pathname'
require 'rubygems'
require 'scrapi'

# Get the URL input.
puts 'Enter a URL:'
url = gets.chomp

# Get the HTML source.
html = nil
open(url) {|source| html = source.read()}

# Define the scraper.
scraper = Scraper.define do
  array :images
  process "img", :images => "@src"
  result :images
end

# Scrape the HTML for images.
images = scraper.scrape(html)

# Create a directory to save the images in.
directory = url.gsub(/http:\/\//, '')
FileUtils.mkdir directory

images.each do |image_path|
  # Determine if image_path is absolute or relative. 
  path = Pathname.new(image_path)  
  if not path.relative? then image_path = url + image_path end

  # Write the image to disk.
  open(image_path) do |source|
    file_name = image_path.split('/').last
    open(directory + '/' + file_name, 'wb') {|file| file.write(source.read())}
  end
end

puts 'Finished...'

Code Snippet: Ruby Word Masher

Posted by Ryan Baxter Sat, 28 Jul 2007 20:54:00 GMT

I can be extremely indecisive about things. So much, in fact, that I even wrote a script to help me choose a name for this website. Is it strange that a random number generator can make me feel better about making decisions? My wife thinks I’m crazy, but she also calls domain names, donames. Besides, I think there is something novel in a computer choosing a name for itself. Anyway… Given some user input, the code below will read words from a file and then mash them together to provide unique combinations. Here is a words.dat file to help get you started. Happy mashing.

#!/usr/bin/ruby

words = Array.new
i = 0

def mash_words(words, mash_count)
  new_word = ''

  1.upto(mash_count) do
    new_word += words[rand(words.length)]
  end

  return new_word
end

begin
  puts 'How many mashed words would you like to create?'
  word_count = gets.chomp.to_i  

  puts 'How many words would you like to mash?'
  mash_count = gets.chomp.to_i  

  input_file = File.new("words.dat", "r")
  while (line = input_file.gets)    
    words[i] = line.chomp    
    i += 1
  end  

  1.upto(word_count) do    
    puts mash_words(words, mash_count)
  end  

  input_file.close  
rescue => err
  puts "Exception: #{err}"
  err
end

Older posts: 1 ... 6 7 8 9