ruby
A few promising Ruby libraries
From the hall of promising Ruby libraries: an FFI binding to Lua, Ruby to Lua, a neat framework for building Twitter bots, TwiBot and some sugar over the Cascading library (which is sugar over Hadoop) for processing large data sets, cascading.jruby
Awesome yak shaves
I was sharing some nefarious plans with Dave Thomas yesterday at the DFW PragProg lunch. He later tipped me off to “tinyrb”:code.macournoyer.com/tinyrb/, which is awesome. It’s a minimal implementation of Ruby that uses “Ragel”:www.complang.org/ragel/, “Lemon”:www.hwaci.com/sw/lemon/ and is inspired by “Potion”:github.com/why/potio… I’ve long had a thing for messing with languages and their implementations, so I quickly ended up at this “great Ragel tutorial”:www.devchix.com/2008/01/1… and then reading about “register machines”:http://en.wikipedia.org/wiki/Register_machine, “context-free grammars”:http://en.wikipedia.org/wiki/Context-free_grammar and “LLVM”:llvm.org/.
I accomplished nothing, but diving into a topic is it’s own reward. Here’s what I’ve concluded:
- I’m super green at this stuff. But I want to go to there.
- There’s too much awesome stuff to do out there: tinker with languages, build apps, visualize data, network things, etc.
- “Marc-André Cournoyer”:macournoyer.com is my hero; not only did he implement tinyrb, but he’s also the guy behind “Thin”:code.macournoyer.com/thin/ and “Refactor My Code”:refactormycode.com
Long story short: I need more time.
Classy Web Development with Sinatra
An admission: I didn’t really do as many awesome things during the Bush administration that I would have liked to. So, now that we have a new president, I’m going to start off right by showing you something awesome.
While it may seem like I’ve had my head up in the clouds of physical computing, urbanism and monads, I’ve been nose down in something else. I’m super-excited to tell you, I’ve just finished the first two episodes of “Classy Web Development with Sinatra”, a screencast for the Pragmatic Programmers.
h2. The Particulars
Sinatra is a great subject. As I point out in the first episode, I think it’s very special in how it puts the smallest possible language over HTTP. Taken with the fun of building your own framework up from scratch, Sinatra apps are a ton of fun to write. Further, Sinatra really shines when you want to write micro-apps or services. Building an API for your Rails app by standing a Sinatra app up next to it to serve the API is a great approach for many applications.
If you’ve known me for a while, you probably know I had at one point aspired to write a book for the Pragmatic bookshelf. That didn’t work out (for the better, I think), but I still wanted to produce something to get the good word out there. I’ve enjoyed the screencast format from the beginning, and I enjoy teaching people interactively, so the format seemed well suited to me. Plus, I’ve always loved the sound of keys clacking in a screencast. Now you can hear my keys!
h2. Shout-outs
Lately, Ryan Tomayko has been absolutely kicking ass with his contributions to Sinatra and Rack. He was kind enough to review the script before we recorded and even put out a maintenance release so that we wouldn’t have to talk around a couple bugs that snuck into the latest release. The finished product is much better for his feedback and guidance.
From the beginning, Mike Clark has been a great mentor and guide through the process of producing a screencast. He helped me write to the beginner’s perspective and avoid speaking in a monotone. Throughout the process, he’s been more helpful and supportive than I could have ever imagined. Needless to say, he’s the foundation that all the goodness of the Pragmatic Screencasts series is built upon.
h2. I want to go to there
Go give the sampler a look, then buy the episodes! If you have questions, drop a message in the forum. And don’t forget to grab the example app and service off GitHub.
DataMapper + Factory Girl
I’ve been toying with “Factory Girl”:www.thoughtbot.com/projects/… lately. The code I’m currently working on needs to generate lots of data before tests run and Factory Girl is handling this well compared to fixtures or coding my own data generators. So, in some unrelated toying with “DataMapper”:datamapper.org/doku.php, I came to wonder if Factory Girl and DataMapper play nicely together.
Turns out they do! The only hitch is you need @dm-validations@ in addition to @dm-core@. Since no one seems to have written this up yet, I thought I’d “share my results”:gist.github.com/49017.
Monads + Ruby = crazy
Guaranteed to boil your brain: do notation in Ruby. You got your monads in my Ruby! He uses ParseTree and Ruby2Ruby to rewrite your code. In other words: heavy.
I’d love to point you to a good monads tutorial, but the monad fallacy prevents me from doing that. I’ll try again once I fully grok them.
Gentlemen's Agreements
BMW and Mercedes produce cars in direct competition. Further, everyone else in the auto industry likes to use them as benchmarks. Read a car magazine and count the superlatives like “more legroom than a Mercedes S500” or “more horsepower than a BMW 330i”. Its a market out there; everyone is incentivised to produce better stuff every time around.
However, you won’t ever find them boasting about top speed[1]. BMW or Mercedes don’t make cars that go faster than 155 MPH. Many moons ago, these car makers made a gentlemen’s agreement to limit their cars to a certain top speed. They probably did this for safety reasons - there just isn’t much need to go that fast and its probably inadvisable for most folks.
Why adhere to these agreements? At any point, BMW or Mercedes could break this agreement and achieve some kind of short-term numerical superiority. But this would end in an arms race that doesn’t really improve the every-day usage of their cars. So really, it’s in each company’s interest to maintain the agreement.
In the land of software development, we have gentlemen’s agreements as well. When I picked up Python in 1999, I learned that they didn’t have a distinction between public, protected and private object attributes. Many decried this, but the general idea was that we’re all adults and do the responsible thing.
Fast forward six years years. At first I was somewhat put off that Rails modifies the standard Ruby libraries. Many people are still put off about this. But I’m OK with it. If you have the chance to drive improvements in an ecosystem without waiting for the core maintainers to release a new version of Ruby, why not?
Many also decry the situation we find around Rails plugins. Its argued that one shouldn’t go around mucking about inside Rails to add functionality. And sure enough, plugins sometimes break when the core team changes Rails, even in the slightest of ways.
No surprise, I’m fine with this. Improving a system from the inside is too appealing to pass up so that I can claim some kind of virtuousness.
Should Rails have a defined internal interface or extension mechanism? Sure, sounds great! But we shouldn’t stop improving it outside the Rails core process just because sometimes we get burned.
The alternative is to define a known set of hooks by which we can modify behavior in a post-hoc fashion. Merb is taking this approach, and I’m eager to see how it works out. My take is that limiting people to extension along axes that the core developers imagined in a pre-hoc manner is too limiting. I hope I am proven wrong.
When it comes to Ruby or Rails, I think we already have a gentlemen’s agreement. We accept that extending systems using the facilities Ruby provides is useful, so we don’t complain too much when we get burned[2]. Accepting this is, in my experience, an empowering aspect of using Ruby that lets me worry about really interesting problems.
fn1. Except maybe for the M and AMG tuner variants of their mass-production cars
fn2. where “too much” is defined by the prudence of the extension mechanism used
Stupid Struct Tricks
All About Struct - there’s always more to learn about @Struct@, unless you’re James Edward Gray. Useful and illuminating for all shades of Ruby developers.
Rich Kilmer speaketh
Ruby’s Best Feature? Rich Kilmer is one of those uncanny developers who can crank out orders of magnitude more good code than your average developer. When he speaks, I always listen.
"with" for Ruby
Use with caution:
That said, @with@ is discouraged in JavaScript. If you can, its better to have methods return @self@ so you can chain like so: @people.get_dressed.put_on_music.and_party!@
Interview with David Flanagan, part 2
The second part of my interview with David Flanagan is online. This time around we talk about the craft of programming in general. Its good stuff.
Interview with David Flanagan
Last week I interviewed the author of The Ruby Programming Langauge, David Flanagan. We posted the first part of it today - Five Questions with David Flanagan, Part 1. The second part will go up next week. Enjoy!
Refactoring to more code
Refactor my code is a neat site where you can post your code and watch others refactor it. I saw an interesting bit of code whiz past and thought I’d take a crack at it.
Removing conditionals from code is one of the little games I sometimes play while coding. Here, I’ve extracted the logic of the conditional into another class. The resulting class is much more code than the original. So why do that?
Well, I say you get a few benefits:
- The logic is now far easier to test. It’s a standalone object now rather than a Rails functional test.
- The flow of what’s being done and tested is more decomposed and easier to follow.
- Most importantly, the code explains itself. No need for comments (which will undoubtedly go out of sync over time) here!
While I delight in deleting code and writing as little as possible, refactoring this to more code seems the right way. What say you?
Update: Make sure you check out Marcel Molina’s refactoring. Its probably better than mine ;)
HTTP wrappers with ease
httparty looks really cool. It’s a little library for making writing tiny REST clients easier. From the examples (edited for length):
class Twitter include HTTParty base_uri 'twitter.com' def initialize(user, pass) self.class.basic_auth user, pass end # which can be :friends, :user or :public # options[:query] can be things like since, since_id, count, etc. def timeline(which=:friends, options={}) self.class.get("/statuses/#{which}_timeline.xml", options)['statuses'].map { |s| s.to_struct } end end twitter = Twitter.new('bob@example.com', 'bobtime') twitter.timeline.each do |s| puts s.user.name, s.text, "#{s.created_at} #{s.id}", '' end
Great job, John!
Practical language kleptomania
Introducing Functor - another library for implementing multiple dispatch/pattern matching in Ruby. This is a great example of what I talked about at OSCON: stealing ideas and applying them to your daily work. I’m particularly impressed with how Dan has applied it to something that isn’t a recursive mathematical function - check out the example of using in a view class.
What Has Ruby Done For You Lately?
When I go to speak about Ruby at non-Ruby groups, my go-to schtick is only mildly subversive. Sure, I tell them that Ruby is a fantastic language that will make them a better programmer. But, I don’t expect them to switch to Ruby right away. Instead, I lead them down the path of borrowing ideas from Ruby and using them in their day-to-day coding, no matter what language they use.
This week at OSCON 2008, I applied the same tact, but I did it on Ruby programmers. See, there are tons of great ideas in languages like Haskell, Io and Erlang. Some translate really well to Ruby and some don’t. But they’ll all twist your brain around in interesting ways.
That’s the idea. Here are the goods: just the slides, the code and the slides. Enjoy!
More modules, please
Jay Fields' Thoughts: Ruby: Underuse of Modules. Modules are your best friend, ya’ll. Use ‘em.
Fake Rails environment
For testing some bits inside of ActiveRecord proper.
module Rails def self.env o = Class.new do def production? true end end o.new end end
Evil and fun. Uses Class.new
, my favorite Ruby method.
Muahahaha.
See me at RailsConf '08
As hordes of Ruby and Rails folks begin the annual migration to Portland for RailsConf, I thought I’d let you know how to find me there this year:
- I’ll join my FiveRuns compatriots (and the epic Rich Kilmer) for Two Apps, Four Daemons and a Gazillion Clients, a panel on The Big Rewrite of FiveRuns Manage. Join us at 11:45 AM on Friday.
- There’s a book signing for all the contributors to Advanced Rails Recipes Friday at 12:35 PM in the Powell’s booth. Come meet me and the other folks who brought you the latest in Rails recipes.
- I’m interviewing the inimitable Geoffrey Grossenbach on Saturday at 3:40 PM in the Heroku booth. Stop by to enjoy the hijinks!
- Rounding everything off, my presentation, Oh, The Fail I’ve Known is at 11:45 AM on Sunday. Come learn from my considerable past mistakes.
That rounds out the conference activities. But I’d be remiss if I didn’t inform you that FiveRuns would like to buy you a drink or two Friday night at Jimmy Maks from 6 to 8 PM. Please to be joining me there!
What I am perhaps most excited about is the RailsEnvy videos that will premiere this weekend. You see, Jason and Gregg were kind enough to invite me to join them in making the funnies this year. Making them was a blast! I’ve seen the finished product and, in my completely biased opinion, I think you’re going to like it.
Of course, I’d love to chat with you (yes, you) at any point in the conference. So if you see me (and I will probably stand out), come say “Hi!” I’m hoping to have something interesting for those that do…
Destructuring assignment in block parameters
…which is just a fancy way to say that this works like I think it should:
>> [['foo', 1], ['bar', 2], ['honk', 1000]].partition { |str, val| val > 999 }
=> [[["honk", 1000]], [["foo", 1], ["bar", 2]]]
Which beats the pants off this:
>> [['foo', 1], ['bar', 2], ['honk', 1000]].partition do |pair|
?> str, val = pair
>> val > 999
>> end
=> [[["honk", 1000]], [["foo", 1], ["bar", 2]]]
So, you see, the array elements get unpacked into @str@ and @val@ inside your block. Which is unexpected, but totally and thoroughly lovely. To my eyes, the former is much easier to read.
Ruby for non-Rubyists
Yesterday I spoke to a pleasant mix of Java, .NET, Ruby, Python and PHP developers at Dallas TechFest. My goal when speaking to enthusiast crowds of this sort is to show the light that I’ve found in my programming journeys over the past couple years. This time around I tried to take a page from the inimitable Richard Feynman by structuring my talk into two sets of “Six Easy Pieces”.
The first part starts off with the stance that programming shouldn’t suck. From there I talk about the intercontinental railroad, Sapir-Whorf, Pattern Languages, the Gang of Four and flattery. In the end, we have an idea of how to better approach programming so we can have fun doing it.
The second half is partially showing off Ruby and partially a gauntlet thrown down to other languages. The main point is to show a progression of ideas I see in lots of Ruby code, from sensible naming to closures ending up with metaprogramming powering declarative programming and internal DSLs. You can implement the ideas from the beginning in any language. However, the ideas towards the end require a more progressively designed language. I’d love to see non-Ruby implementations of the programs towards the end of the presentation, if only for comparison and Rosetta Stone purposes.
Thanks to everyone who was in attendance and especially those who stopped to chat with me before and after the presentation. Without further ado, please enjoy Six Easy Pieces (Twice Over).