Scary Ruby

12 01 2010

We all know that Ruby’s a flexible beast, but just how much you can bend it is almost scary. How about inheriting from a class randomly chosen at runtime? Sure, no problem:

I dare you to find a use case for this ;-)

And in case random isn’t good enough for you, why not have the user choose the superclass for you?


Fun with Sinatra, Heroku and MongoDB

06 12 2009

I’ve been toying around with the idea for a small website lately, but never actually got around to do it. In an attempt to clear out my personal to do list I finally motivated myself to start yesterday, and I have to say the following combination of tools is not only insanely efficient, but also really fun to work with:


  • Sinatra, “a DSL for quickly creating web applications in Ruby with minimal effort”. I recommend using it in combination with Mongrel, Shotgun and Haml.

  • Heroku, a Ruby cloud hosting platform. Small sites are for free and Heroku’s git-based workflow just feels so natural. You can also manage your gem dependencies and set up environment variables, which made my life a whole lot easier.

  • MongoDB, “a scalable, high-performance, open source, schema-free, document-oriented database”. In this specific case I used MongoHQ for the database hosting, since they were nice enough to provide me with a beta account. I stored all the connection information for MongoHQ in environment variables as described above:


With this combination I was able to go from zero to mostly finished (I still need to write some of the content and make/steal a stylesheet) in very little time, while actually having fun! Thanks everybody for providing the Ruby community which such awesome tools! :-)


Fun with Twitter and Ruby

23 11 2009

I’m currently toying around with some ideas for Twitter bots etc. so I had a look at some of the available gems out there. Sometimes Ruby makes stuff almost too simple… ;-) Here are a few nice snippets of what you could do with a couple of minutes time and some Ruby:

Automatically translate all tweets for a given keyword:

Daemonize the above:
Alternatively you can also follow a userid instead of a keyword and daemonize the whole thing, thus making it super easy to create a bot which posts translations of Matz’s tweets:

If you put this into a file like transbot.rb, the command ruby transbot.rb will give you all the regular daemon commands like start, stop, etc.

Ruby is trendy
Curious of getting a list of current trends on Twitter, without hashtags? There you go:

Combining all these ideas you could easily write a bot that follows the current Twitter trends and posts translations of them in only a couple of lines. :-)


What's new pussycat?

06 10 2009

Quite a bit actually:


unsavory now available as gem

08 09 2009

unsavory is now available as a gem, which means that you can comfortably install it like this:

# Only if GitHub isn't in your gem sources yet
$ gem sources -a http://gems.github.com 
$ sudo gem install citizen428-unsavory

Rubygems will automatically create a wrapper-script named “unsavory”, which you can use to start the program so you finally can get rid of all these outdated bookmarks.


Pascal vs. Ruby

29 06 2009

On ruby-talk somebody was asking for a method which will be used to generate a random string, by returning either a lowercase letter or one of the digits 0-9 when called. As an example he posted the following Pascal program:

function GetRandomChar: char;
var
 r: integer;
begin
 r := random(36);
 case r of
   0..25: result := chr(ord('a') + r);
   else : result := chr(ord('0') + r);
 end;
end;

“Translating” this to Ruby, this is what I got:

In your face, Niklaus Wirth! ;-)

P.S. Actually I do have fond memories of the good old Turbo Pascal days.


Quick and dirty lazy lists in Ruby

18 06 2009

Hash.new with a block is a sexy beast: you can specify default hash values and when a key is first used, the value will be calculated and inserted into the Hash. Based on that behavior I took a couple of minutes to hack together a small proof of concept class for lazy lists:

As I said, this is quick and dirty, especially since you have to pass the entire Hash.new block to LazyList.new right now. Other than that I quite like it though. I know there are at least two other lazy list implementations for Ruby, but it seems like both haven’t been updated in a while and I don’t particularly like their interfaces. Dunno, if I manage to simplify list definition, I may actually try to develop this into something. Don’t hold your breath though…


Unsavory updates

16 06 2009

Today I felt like playing around with unsavory a bit more, which led to some minor improvements:


  • code reorganization: the delicious class got moved to a separate file in lib/ and got a new method for easier retrieval of the URLs array

  • login credentials can now be read from a config file, thus making HighLine optional


Next on my list is packaging this up as a gem so people can simply install it with ‘gem install unsavory’.


Review: The Well-Grounded Rubyist (Manning Publications)

09 06 2009

As part of Rubylearning’s current book promotion I’m reading The Well-Grounded Rubyist by David A. Black. Here are my thoughts on the book:

If you are new to Ruby, this may very well be the book you are looking for, since the author was really serious about the “well-grounded” in the title. Together the first six chapters form Part 1, aptly called “Ruby Foundations”. Here you’ll learn about objects, modules, classes, self and control-flow techniques. Although this part may not be the most interesting for more experienced Rubyists, it’s certainly well-written and manages to present a lot of very fundamental Ruby right at the beginning. True, at first I was a bit surprised to see that singleton methods were – implicitly – introduced before classes, but when you follow the author’s logic, it all makes a lot of sense. What I really like about this approach is that it exposes the reader to concepts needed for some quite advanced Ruby coding right away, and in a very light-hearted and “natural” manner. Well done!

Part 2 (“Built-in classes and modules”) covers everything from strings, over symbols to regular expressions and file I/O. What I really like about this part is that the author dedicated two whole chapters to collections and iterators/enumerators, which are essential for everyone striving to become fluent in Ruby.

Last but not least Part 3 (“Ruby dynamics”) talks about singleton methods, procs, lambdas, Symbol#to_proc, the various eval methods, bindings and introspection, thus equipping the reader with all the necessary tools for metaprogramming, one of the many things that make Ruby that sexy little beast it is.

Oh yeah, since I didn’t mention this before, “The Well-Grounded” Rubyist” covers Ruby 1.9.1, which means you’ll learn about the coolest Ruby around. Don’t worry though, most of what you read will also apply to 1.8.6, but isn’t it about time that we all slowly moved on?


unsavory — get rid of stale Delicious bookmarks

06 06 2009

While browsing through my Delicious bookmarks the other day, I realized that over time I had accumulated quite a few dead links (about 5% of my collection). I then looked for a simple tool to automatically remove them, but couldn’t find one that appealed to me, so I wrote my own script called unsavory which you can find on GitHub:

http://github.com/citizen428/unsavory/tree/master

It uses HTTParty to generate a list of all your bookmarks, which then get checked individually with Net::HTTP. Every link that returns an HTTP status code of 404 will automatically be removed (no questions asked, no undo), links with a status code other than 200 (OK) won’t be changed but will display some information in case you want to fix them manually. Here’s some example output (links anonymized for this post):

  Enter Delicious username: citizen428
  Enter Delicious password: *********

citizen428 has 664 bookmarks. Processing URL #0001: OK Processing URL #0002: OK Processing URL #0003: OK Processing URL #0004: OK Processing URL #0005: OK ... Processing URL #0013: 405: http://... ... Processing URL #0074: 302: http://... ... Processing URL #0086: Connection reset by peer – https://...

Not bad for under 60 lines of code. :-) I hope this is useful to some of you, I do have some features I plan on adding to this in the future.


Review: Functional Programming with Clojure (PeepCode screencast)

25 05 2009

A couple of month ago I first heard about Clojure, a Lisp-like language sitting on top of the JVM. Alas I didn’t yet have time to have a closer look at it, so I decided to get myself the PeepCode screencast.

This 65 minute video is the first to use PeepCode’s new post-production workflow, and it’s very well done! In just a little over an hour you go from learning about Clojure’s basic concepts and syntax to writing a multi-user text based adventure game, tackling topics such as data structures, thread safety, lazy collections, unit testing and packaging of Clojure apps. All of that is clearly presented and easy to follow, which makes for an ideal first overview of the language. If you are curious about Clojure but have little time, consider investing the money for this screencast!

On a more general note it’s interesting to see that more and more languages seem to target the JVM. I never really had any interest in Java and also totally ignored Groovy, but now that JRuby, Scala and Clojure entered the stage, I might start looking into the Java platform a bit more. Especially Scala with its mixed Ruby/Haskell feel appeals to me, but as antifuchs showed, there’s also pretty neat stuff (GitHub project) one can do with Clojure.


Most used shell commands

25 05 2009

I recently found a bash snippet which creates a list of the commands in your .bash_history file and how many times you invoked them:

history | awk '{a[$2]++ } END{for(i in a){print a[i] " " i}}'|sort -rn|head

Although there was no real point in doing so, I felt the need to write a short Ruby script to do the same:

Here’s the output on my MacBook:

$ command_stats | head
time: 75
cd: 68
ls: 66
git: 35
cat: 32
irb: 20
awk: 17
ruby: 15
scala: 15
vim: 12

If you are surprised by how many times (no pun intended) I called time, it’s just because I was benchmarking Project Euler solutions in several languages, everything else is quite regular (and suggests I don’t use the Finder much ;-) ).


Review: Meet MacRuby (PeepCode screencast)

24 05 2009

This afternoon I had the time to finally watch the PeepCode Meet MacRuby screencast.

In case you don’t know MacRuby, it’s a Ruby interpreter sitting on top of Objective-C and OS X core technologies (see also here).

During the 74 minute screencast you will build a basic but functional Twitter client, and in the process learn about MacRuby and Cocoa basics, using Xcode and InterfaceBuilder to develop and bundle your application and many other interesting topics.

The screencast is very well structured, easy to follow and full of good and practical information, including perks and rough edges of the current MacRuby version. All in all a really enjoyable and informative video, which is well worth US$9 (or less if you buy packs of credits)!


Review: Ruby in Practice (Manning Publications)

18 05 2009

I read Ruby in Practice for the upcoming book promotion on RubyLearning, and I have to say it’s a pretty neat book which will be well worth your time and money. Over the course of 360 pages Jeremy McAnally and Assaf Arkin tackle lots of different topics of interest to developers. The book is structured in 3 main parts:

  • Ruby techniques: Gives a general introduction to Ruby’s strength (which sometimes reads as a bit of a sales pitch), BDD and TDD, as well as scripting with Ruby (including OLE and OSA).
  • Integration and communication: This part covers Rails, web services in general (HTTP, REST, SOAP), automating communication with email and IM, asynchronous messaging and deployment options.
  • Data and document techniques: This part talks about databases, structured text, authentication, searching, indexing and document processing.

Chapters usually present the reader with a problem, then show an example solution which usually makes good use of existing libraries and then finish with further discussion on the topic (alternative ways to implement it, pitfalls in using the shown solution in “real life” scenarios etc.). For people with previous knowledge of Ruby this book is a good read, which shows how the dynamic nature of the language combined with the quite big amount of readily available libraries enable developers to quickly and efficiently find solutions to common problems. I sometimes do have minor quirks with some of the code, but that’s just personal preferences and being nitpicky. All in all it’s a very solid book which I enjoy quite a lot.


Create your own (Ruby) API browser in 3 easy steps

17 05 2009

  • Step 1: Download Fluid, an awesome little application to create site specific browsers.
  • Step 2: Find some online API documentation. For Ruby I recommend railsapi.com or RubyBrains.
  • Step 3: Create your app in Fluid:
  • Fluid

Here’s an example screenshot of a site specific browser for RubyBrain.com:

Fluid RubyBrain

Of course this still requires you to have a working internet connection, but you could always use a local version of the API docs when creating the app. On a related note you should also check out Goo which is a nice alternative to gem server on OS X.