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.
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).
Beautiful multi-line blocks in Ruby
“I need a new drug”:http://youtube.com/watch?v=MMSFX1Vb3xQ. One that won’t quit. One that will let me sensibly structure the use of blocks in Ruby such that they can run across multiple lines and yet still chain blocks together.
OK, so its not really a drug I need, per se. Though, I’m sure what Huey Lewis really needed was a new drug. But what I need is a convention, or perhaps some syntax. It should say to you, “HEY. Adam’s doing something clever with blocks here. Keep your eyes open.”
I find myself desiring a new syntax and/or convention, when using blocks. I’ve been trying to write in a more functional style lately, especially a pure-functional style wherein you never call a method for its side-effects. I don’t think I’m the only person doing this. Jim Weirich sort of alluded to it in a post about “when to use @do/end@ vs. braces”:http://onestepback.org/index.cgi/Tech/Ruby/BraceVsDoEnd.rdoc. Rick DeNatale “took it a step further”:http://talklikeaduck.denhaven2.com/articles/2007/10/02/ruby-blocks-do-or-brace. I want to lay it bare.
Let’s start with something innocuous:
ary = [1,2,3]
result = ary.map do |n|
x = n * 4
end
result # => [4, 8, 12]
You get the value back of each object in the array, mapped to the result of calling the block. Fun times. Now, let’s put it on one line and do something clever with it.
ary.map { |n| n * 4 }.select { |n| n == 4 } # => [4]
Now we’re cooking! Ruby’s syntax allows us to chain methods and blocks. Which turns out nice in this case where I want to filter down the array of mapped values. But let’s pretend we need to do something clever in those blocks.
ary.map { |n|
n * 4
# Some
# clever
# things...
}.select { |n|
n == 4
# More
# clever
# things...
}.any? { |n|
n == 4
# Gratuitiou
# clever
# things...
} # true
That’s the best I could come up with for chained, multi-line blocks. It looks “Weirichian”. Despite that, it kinda makes me vomit in my mouth.
So, since “I got awesome feedback on my last question of taste”:http://therealadam.com/archive/2008/04/28/can-i-send-you-a-message/, I’m tapping you, my favorite Ruby developer, for more. The ground rules are that you can’t extract the logic into a real method and you can’t jam everything onto one line. You have to use multi-line blocks. What looks good to you here?