Tag Archives: ruby

Searching Twitter with Ruby

After seeing this a few days ago, I thought it’d be fun and easy to whip up a little script that would dump tweets from around my area. Unfortunately, it was neither. I won’t bore you with my troubles, suffice it to say GitHub has now been added to my list of gem repositories.

I haven’t gone through much of the actual api yet, but so far it looks great. I did play around with a few different wrappers before finally getting down to business with twitter_search, which is nice, and thin, and jived nicely with my goal.

So here’s the code to fetch the last 15 tweets from ( thanks geocoder! ) my area. Simple, eh?

require 'rubygems'
require 'twitter_search'

tweets = TwitterSearch::Client.new.query :geocode => "28.599630,-81.289176,2mi"

tweets.each do |t|
  puts "@#{t.from_user} - #{t.text}n"
end

The next step is to figure out how to look up geocodes automatically, and maybe build some sort of web interface. But not tonight.

Gosu Extensions Update

tests_complete

I’ve finally finished updating my Gosu Extensions. It’s far from perfect, but it’s in a good spot and I’m relatively happy with it. It feels good to get something “done”.

Although my coding process hasn’t been 100% TDD, I would say at least it’s been test centric and irregardless of whether I actually do anything with this, I think it’s been a good experience.

I plan on updating some of my “games” to use this new version, so I can see if these extensions actually save me any work.

Here are a few of the highlights

  • JavaScript like elements and events ( on_click, on_focus etc )
  • Wrappers for Gosu Images, Samples, Fonts and Text
  • Bounding Boxes for basic collision detection
  • Easy cursor support
  • Basic grid / matrix support
  • Basic scheduling system

Enough chit chat, Download the code!

Implementing Prototype’s Event.observe in Ruby – Take 2

I revisited my Event.observe proof of concept and tidied it up a bit with a little help from stackoverflow.com.

Here’s how it do

This here defines a method to determine which method is currently running. There’s a slicker way to do this in 1.9 and you can read about them both on stackoverflow.com.

module Kernel
 private
  def current_method_name
    caller[0] =~ /`([^']*)'/ and $1
  end
end

Here’s my actual observer class, named after it’s inspiration.

class Event

  def initialize
    @events = []
  end

  def observe object, method, callback
    handle   = Handle.new self, object, method, callback
    @events << handle
    handle
  end

  def delete handle
    @events.delete handle
  end

  def call object, method
    handle = Handle.new self, object, method
    @events.each do |e|
      e.call if e.shares_type_with 
    end
  end

end

And finally there's a basic handle class:

class Handle

  attr_reader :observer, :object, :method, :callback

  def initialize observer, object, method, callback = nil
    @observer  = observer
    @object    = object
    @method    = method
    @callback  = callback
  end

  def shares_type_with? handle
    object == handle.object && method == handle.method
  end

  def call
    callback.call
  end

  def stop_observing
    observer.delete self
  end
end

And here's how you use it, In the following example we want our "second" Test_Object to run it's test_method whenever we run the same method for our "first" object.

The important thing here is the "notify" method, you'll need to drop this method into whatever you'd like to be able to observe. If you wanted to be able to observe everything you could always loop through the methods, alias and override.

class Test_Object

  def initialize observer, label
    @observer = observer
    @label    = label
  end

  def notify method
    @observer.call self, method
  end

  def test_method
    puts "Calling => #{@label}"
    notify current_method_name 
  end

end

observer = Event.new

first    = Test_Object.new observer, "First"
second   = Test_Object.new observer, "Second"

h1  = observer.observe(
  first,
  "test_method",
  second.method :test_method
)

first.test_method

# Calling First
# Calling Second
#=> nil

And we can drop the handle by simply calling it's stop_observing method

h1.stop_observing
first.test_method

# Calling First
#=> nil

That's it.

Download the Proof of Concept!

Ruby-er than you!

When I first started with Ruby, I wrote it like I would any other language: Classes, methods, loops, conditionals. It worked, and I appreciated the sweet syntax, but I wasn’t taking full advantage. It’s been a while since I first began with my hobby language, and slowly but surely, my Ruby is becoming more Ruby-like.

I’ve picked up a few tricks and I’m getting better at leveraging the more (see below) advanced features appropriately and effectively. Enough so that I’m often horrified by things I wrote just a few months back. It can be a tad discouraging, but ultimately it’s a good thing because it means I’m getting better.

Besides, as a co-worker of mine likes to point out, how awful would it be if the situation where reversed?

Newayz, here are a few links to some of them fancy fixin’s I was talking about:

Implementing Prototype’s Event.observe in Ruby

I love Prototype. I wanted to implement something akin to Event.observe in some of the gui applications I’ve been playing with. The code’s fugly, but it’s a first pass and I just finished my last Netflix.

Example JavaScript Implementation is pretty:

a = new Test_Object( "First" )
b = new Test_Object( "Second" )

Event.observe(
  a,
  "test_method",
  b.test_method
)

Event.observe(
  b,
  "test_method",
  function(e) { new Test_Object("Third").test_method() }
)

Example Ruby Implementation..not so pretty.

$event = Event.new
a      = Test_Object.new( "First" )
b      = Test_Object.new( "Second" )

$event.observe(
  a,
  "test_method",
  b.method( "test_method" )
)

$event.observe(
  b,
  "test_method",
  Proc.new { Test_Object.new("Third").test_method }
)

a.test_method

Yep, that’s a global. I’m still working on it. Any ideas would be welcome!

Download the Ruby code!

ID3Mapper – A Ruby ID3 renaming utility

I have a Zune. At the time I had a working Windows box, hated iTunes, and thought I would actually use the radio tuner and I actually really like it. The desktop software…not so much.

There’s only a Windows version, it runs horribly when you have a lot of artists, it only picks up half of my podcasts. I figured out a while back that the reason my podcasts weren’t showing up had to do with the id3 tags, so I wrote a horrible little ruby script ( utilizing id3lib-ruby ) that would set the correct genre of “podcast” for everything in my podcast directory.

For fun, I thought it would be cool to write a little desktop app using the most popular Ruby gui toolkit Shoes that would make it easier for me to correct some other id3 tag irregularities in my media collection.

The first step was to re-factor my id3 script. I’ve been tooling around with automated testing a bit over the last couple months and I thought this would be an excellent chance for me to attempt a full-on test first methodology. I did, and I’m pretty happy how it turned out, although it certainly didn’t save me any time.

Click to download the new and improved id3mapper.

I’ll eventually package this up into it’s own module, but for now this is how it works:

require '../settings'
i = ID3Mapper_Console.new

i.set_artist "/home/joe/Podcasts/WNYC Radio Lab", "Radio Lab"
i.set_genre "/home/joe/Podcasts/WNYC Radio Lab", "podcast"

Scraping and Saving Flickr Images with Ruby

I’ve been playing around a bit more with the black arts of spidering and scraping in Ruby and I’m still amazed by how easy it is to do. For fun I whipped up a little script that will spider a Flickr photostream and download all the images.

Flickr provides a wonderful api and there’s even a great Ruby interface for it, so this script is entirely futile. But it was fun and educational.

Usage

ruby init.rb yourusername /location/to/save

Download it!

Finding and Fixing Broken Images with Ruby

A family members was having a problem with some mixed up image names on a static html site. I could have fixed it manually in a few shakes, but that’s no fun. Instead I used hpricot to scrape, open-uri to test for broken-ness, Find to search and some good old fashion regex to correct.

This was my first time messing around with hpricot and I found it to be powerful and easy to use, two thumbs up. I foresee some scraping and spidering posts in the near future.

On to the code:

My final script was a bit hairy so I broke out the bit I used to find the broken images.

If you run the script it’ll print the offending paths to screen:

ruby image_scanner.rb http://site.com/busted.html

Or you can call the get_broken_images method to get an array back:

require 'image_scanner'
scanner = Image_Scanner.new
broken_images = scanner.get_broken_images "http://site.com/busted.html"

In case you’re interested, I’ve also uploaded the full code that I used to search for and correct the images although it’s implementation specific, riddled with lazy and is poorly tested. Read the disclaimer!

Just run it and be amazed!

ruby image_scanner.rb http://site.com/busted.html /media_folder /busted.html /fixed.html

Download only the broken image scanner
Download the full script

Project Euler: Problem 11 in Ruby

This one was reminiscent of problem #8. Very straight-forward. I got the wrong answer the first time because I forgot to count BOTH diagonals. Silly me.

Problem #11

What is the greatest product of four adjacent numbers in any direction (up, down, left, right, or diagonally) in the 20×20 grid?

grid = "08 02 22 97 38 15 00 40 00 75 04 05 07 78 52 12 50 77 91 08
49 49 99 40 17 81 18 57 60 87 17 40 98 43 69 48 04 56 62 00
81 49 31 73 55 79 14 29 93 71 40 67 53 88 30 03 49 13 36 65
52 70 95 23 04 60 11 42 69 24 68 56 01 32 56 71 37 02 36 91
22 31 16 71 51 67 63 89 41 92 36 54 22 40 40 28 66 33 13 80
24 47 32 60 99 03 45 02 44 75 33 53 78 36 84 20 35 17 12 50
32 98 81 28 64 23 67 10 26 38 40 67 59 54 70 66 18 38 64 70
67 26 20 68 02 62 12 20 95 63 94 39 63 08 40 91 66 49 94 21
24 55 58 05 66 73 99 26 97 17 78 78 96 83 14 88 34 89 63 72
21 36 23 09 75 00 76 44 20 45 35 14 00 61 33 97 34 31 33 95
78 17 53 28 22 75 31 67 15 94 03 80 04 62 16 14 09 53 56 92
16 39 05 42 96 35 31 47 55 58 88 24 00 17 54 24 36 29 85 57
86 56 00 48 35 71 89 07 05 44 44 37 44 60 21 58 51 54 17 58
19 80 81 68 05 94 47 69 28 73 92 13 86 52 17 77 04 89 55 40
04 52 08 83 97 35 99 16 07 97 57 32 16 26 26 79 33 27 98 66
88 36 68 87 57 62 20 72 03 46 33 67 46 55 12 32 63 93 53 69
04 42 16 73 38 25 39 11 24 94 72 18 08 46 29 32 40 62 76 36
20 69 36 41 72 30 23 88 34 62 99 69 82 67 59 85 74 04 36 16
20 73 35 29 78 31 90 01 74 31 49 71 48 86 81 16 23 57 05 54
01 70 54 71 83 51 54 69 16 92 33 48 61 43 52 01 89 19 67 48".split ' '

directions = 4
products   = Array.new grid.size * directions, 1
size       = Math.sqrt(grid.size).to_i
seq        = directions
n          = 0

def fetch grid, size, i, j
  if i >= size || j >= size
    return 0
  end
  grid[i * size + j].to_i
end

size.times do |i|
  size.times do |j|
    seq.times do |k|
      products[n + 0] *= fetch grid, size, i, j + k
      products[n + 1] *= fetch grid, size, i + k, j
      products[n + 2] *= fetch grid, size, i + k, j + k
      products[n + 3] *= fetch grid, size, i + k, j - k
    end
    n += directions
  end
end

puts products.sort.pop

Project Euler: Problem 10 in Ruby

This one was a breeze after figuring out #7. Straight-forward and fugly. Shush.

Problem #10

The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

Find the sum of all the primes below two million.

#The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.

#Find the sum of all the primes below two million.

$max   = 2_000_000
$stack = [2,3]
$total = 5
$store = Math.sqrt($max).floor
n      = 1

def is_prime n
  max = Math.sqrt(n).floor
  $stack.each do |i|
    if i > max
      return true
    end
    if n % i == 0
      return false
    end
  end
  true
end

def store n
  if $stack.length < $store
    $stack << n
  end
  if n >= $max
    puts $total
    exit
  else
    $total += n
  end
end

while true do

  if is_prime n += 4
    store n
  end

  if is_prime n += 2
    store n
  end

end

puts $total