Saturday, September 13, 2008

Ruby in the browser at Rubyconf

Just got the news this week that my submission on ruby in the browser, has been accepted for Rubyconf. This looks like an awesome conference and I am really psyched to be included. It is also inspiring me to do some more work on rubyjs_on_rails and try to finish up an activeresource client. I'll be hacking on that in whatever free time I have available this weekend.

I'm also thrilled that I get to be part of another dialogue session with Joe O'Brien and Jim Weirich. This session will be a similar format to our railsconf dialogue which seemed to go over pretty well. It's always a ton of fun to collaborate with these two phenomenal guys.

Monday, August 25, 2008

rubyjs_on_rails hackfest at erubycon

I had a really fun time hacking on rubyjs at eRubycon. It's amazing how much more fun and productive it is to hack with someone else than by yourself. Thanks to Corey Haines for staying up late at the hotel being my hacking buddy. As a result, we now have what will be the beginning of an ActiveResource client for rubyjs_on_rails. I generated a simple scaffold resource example called Customer with a few fields. I then created a Customer class in the view and started getting it to speak restfully with rails. Here's the result:


require 'dom_element'
require 'json'
require 'rwt/HTTPRequest'

class Customer


attr_accessor :attributes

def initialize(attrs)
@attributes = attrs
end

def method_missing(method, *args)
if method =~ /(.*)=$/
attributes[$1] = args[0]
elsif attributes[method]
attributes[method]
else
super
end
end

def self.main
@name = DOMElement.find("name")
@address = DOMElement.find("address")
find_button = DOMElement.find("choose_customer_button")
save_button = DOMElement.find("save_button")
customer_id_text = DOMElement.find("customer_id")

find_button.observe("click") do |event|
Customer.find(customer_id_text["value"]) do |customer|
@name["value"] = customer.name
@address["value"] = customer.address
@customer = customer
end
end

save_button.observe("click") do |event|
@customer.name = @name["value"]
@customer.address = @address["value"]
@customer.save
end

rescue StandardError => ex
puts ex
end

def self.find(id)
HTTPRequest.asyncGet "/customers/#{id}.json" do |json|
hash = JSON.load(json)
yield Customer.new(hash["customer"])
end
end

def save
request_json = {:customer => attributes}.to_json
HTTPRequest.asyncImpl "/customers/#{id}.json", "PUT", request_json, "application/json" do |json|
self.attributes = JSON.load(json)
end
end

def to_json
attributes.to_json
end
end



The first part I did was find. I've had that done for a couple weeks. This was super easy because rubyjs and rails support json so easily. The only odd bit is that it takes a block instead of returning a result. This is because the find call does an ajax request, and the a in ajax stands for.. you guessed it, asynchronous. Passing a block in makes it nice and simple to handle the result easily though.

The part I got working at rubycon was the save. This proved to be much easier than I thought it would be as well due to rails now supporting json updates natively. The controller code doesn't even need to be aware that the parameters are coming in as json, you can access param[:customer] the same as you would if it was coming from a normal form submission. I had to be sure and specify it was a PUT request when I sent it in, which I didn't realize was as straightforward to do as it is. I monkeyed around with a _method param and all sorts of stuff before realizing I could just tell the HTTPRequest object what kind of request I wanted to make. Duh.

Though this is a specific example right now, I think a large portion of this code should be easy to extract out into an ActiveResouce client base class. I haven't had any more time to hack on this since erubycon, sadly, but this is what I'll be focusing on when next I do. Also, I just now put up a new repo on github to hold this and any other rubyjs_on_rails example code: git://github.com/superchris/rubyjs_rails_example.git. Enjoy!

Wednesday, July 9, 2008

Announcing rubyjs_on_rails: ARAX sans silverlight

So maybe you're like me: sure javascript is nice and all but you really like ruby better. And as we move toward richer web apps, there are times it sure would be nice to write some of the client side code in ruby. Along comes M$ with their sexy silverlight DLR magic to make it happen. But you're suspicious: it requires a browser plugin, and can you really trust that it will be there on all the platforms you want to support. Sure, maybe M$ has learned how to play nice and it will be different this time. Maybe.

Well, you can quit holding your breath and exhale, girls and boys. You can write ruby code that runs in the browser right now. Today. No plugin or nuthin. So here's how. First, you'll need my forked version of the rubyjs ruby to javascript compiler. It's a little like GWT for you Java folk. Get it here. Sorry, until githubs gem building process decides to show me some love you'll need to download and install it locally with:

gem install --local rubyjs-0.8.1.gem

Next, you take standard rails app and install my superfantastic* rubyjs_on_rails plugin like so:

script/plugin install git://github.com/superchris/rubyjs_on_rails.git

So what did you get? Well, basically, one measly helper method. Sad, huh. Hey! Don't judge me! Cool your jets and let's see what it does already. First make a rails controller with a single action. Any old action will do, but let's imagine it's called hello. Go find hello.html.erb and put a single button button that doesn't do anything in it like so:

<input type="button" id="button" value="Say Hello">

Now let's write some ruby code to respond to the button click. Make a file called hello.rb in the same directory as your view and put this in it:

require 'dom_element'

class Hello
def self.main
button = DOMElement.find("button")
button.observe("click") { puts "Hello from rubyjs!"}
end
end

DOMElement is a class provided by the rubyjs gem that makes it easy to, surprise surprise, work with dom elements. In our case we just use it to grab hold of our button and observe the click event with a block of ruby code. Kind of cool I think.

But how to get this code into the brower? You remember earlier when I said all this plugin gives you is one measly helper method and you were all "Meh. I am sooo not impressed." Well now let's see it in action. Add this to your view right below the the button:

<%= rubyjs "Hello", "main" %>

Now hit this action in your browser. Click the button and you'll see your ruby block fire. The rubyjs helper method goes and finds hello.rb, compiles into javascript, and outputs a script tag to serve it up. The arguments to it are the class name and and a class method to invoke. It needs to be a class method; As this is the entry point to the code there is no instance yet to invoke methods on.

So that's it. Ruby running in the browser. You're welcome.

*Your superfasticalness may vary. No actual superfantasticness is either expressed nor implied by this blog post

Thursday, July 3, 2008

eRubyCon: Be There!

Just a quick little post to get the word out to my readers about eRubyCon in Columbus, OH Aug. 15-17th. It's shaping up to be an awesome conference. And the early bird rate makes it the best conference deal I've ever heard of. Heck, even the post early bird rate makes it the best conference deal I've ever heard of. So register already. You know you wanna.

Wednesday, June 4, 2008

Write your javascript in ruby with rubyjs

I was inspired by Nathaniel Talbott's awesome railsconf talk to do some hacking. I had a lot of fun, and I think I came up with something worth sharing, so here it is. My willing victim was rubyjs, Michael Neumann's excellent little project I mentioned in an earlier post. If you want to play along at home, the first thing you'll need to do is fetch my code like so:
git clone git://github.com/superchris/rubyjs.git

There are some things in my repo that haven't made it into the gem version of rubyjs yet. My hack was a little "port" of the hangman example from Tapestry. It's there in examples/hangman. You can try it here. Or if you're so inclined, you can build it your dang self by running:

rake "examples/hangman/hangman.js"

This command uses a rake rule to run the rubyjs compiler which compiles hangman.rb to hangman.js.

So let's see some code how about, hmm?

class DOMElement
def initialize(element)
@dom_element = element
end

def observe(event, &block)
element = @dom_element
`
if (#<element>.addEventListener) {
#<element>.addEventListener(#<event>, #<block>, false);
} else {
#<element>.attachEvent("on" + #<event>, #<block>);
}
`
nil
end

def [](attribute)
element = @dom_element
`return #<element>[#<attribute>]`
end

def []=(attr, value)
element = @dom_element
`#<element>[#<attr>] = #<value>;`
nil
end

def self.find_js_element(element)
`return document.getElementById(#<element>);`
end


def self.find(element)
dom_element = self.find_js_element(element)
DOMElement.new(dom_element)
end

#
# Gets an HTML representation (as String) of an element's children.
#
# elem:: the element whose HTML is to be retrieved
# return:: the HTML representation of the element's children
#
def inner_html
elem = @dom_element
`
var ret = #<elem>.innerHTML;
return (ret == null) ? #<nil> : ret;`
end

#
# Sets the HTML contained within an element.
#
# elem:: the element whose inner HTML is to be set
# html:: the new html
#
def inner_html=(html)
elem = @dom_element
`
#<elem>.innerHTML = #<html>;
return #<nil>;`
end

end

The first class you see here is DOMElement. This gives some basic dom manipulation abilities in a ruby friendly way. I got this working by looking at the work Michael had done on porting GWT to ruby and extracting the bit I wanted and "rubifying" it a little. Basically, you can find elements by id, observe events with ruby blocks, and get/set attributes and inner html. Pretty simple, but has what I need. I should probably extract this into a separate file in rubyjs in case other people want it. You can also see lots of examples of how rubyjs and javascript talk to each other here.

Then it's on to the hangman code. First it's worth looking at the html so you can see what dom elements the code refers to:

And finally here's the hangman class:

class Hangman

attr_accessor :word, :letters, :misses

MAX_MISSES = 6

def initialize
@word = "snail"
@letters = @word.split ""
@guessed_letters = {}
@letters.each { |letter| @guessed_letters[letter] = false }
@misses = 0
@scaffold_div = DOMElement.find("scaffold_div")
@letters_div = DOMElement.find("letters")
@guess_input = DOMElement.find("letter")
@guess_button = DOMElement.find("guess")
@guess_button.observe("click") do
guess(@guess_input["value"])
end
@letters_div.inner_html = display_word
end

def display_word
letters.collect do |letter|
@guessed_letters[letter] ? letter : "_"
end.join
end

def guess(letter)
if letters.include?(letter)
@guessed_letters[letter] = true
@letters_div.inner_html = display_word
puts "You win!" if won?
else
@misses += 1
@scaffold_div.inner_html = "<img src='scaffold-#{@misses}.png' />"
if lost?
puts "You lost!"
@guess_button["disabled"] = true
end
end
@guess_input["value"] = ""
end

def lost?
@misses >= 6
end

def won?
@guessed_letters.values.each do |guessed|
return false unless guessed
end
return true
end

def self.main
hangman = Hangman.new
rescue StandardError => ex
puts ex
end
end

First you see the initialize method. Here is where we lookup our DOM elements, setup a Hash of which letters are guessed yet, and bind a block to the click event of our guess_button. Next comes the display_word method, which displays each letter or a blank if it's not been guessed.

The meat of the matter is in guess_letter, which is pretty simple. If the letter guessed is in the word we mark it, redisplay the word with the guessed letter and check if the user has won. If not, we update our miss count, display the right image, and check to see if the user lost. Won? and lost? are both trivial and not worth talking about.

Well, I had a lot of fun hacking on this. I think rubyjs has a good chance to be really useful as well as fun. It needs some love, certainly, but one of the things I did was start of woefully inadequate port of miniunit I'm calling microunit. It's in rubyjs/lib. This should make it easier and, I think, funner, to flesh out the core library for rubyjs.

For next steps I may expand on this example some. I'm thinking it would be a blast to tie to a Rails backend that gives me random words (right now it is always the same word :( ) or stores scores or some such foolishness. I could use this as an excuse to build an ActiveResource client for rubyjs and maybe a rubyjs on rails plugin.

If anyone cares about this, drop me a comment and let me know. Or if you think it's utterly stupid, tell me why. I promise to read all your comments and do whatever I feel like doing anyways :)

Tuesday, June 3, 2008

Back from Railsconf 2008

Wow, that was fun. Here's a quick recap of my personal highlights of Railsconf 2008.

Our Modelling Dialogue session

So I'm self-centered, but this was the talk I had the most concern about since I was in it. To be honest I had no idea how this was going to be received, so I was relieved and excited by the great response. I had this vision of all our laugh lines receiving the dead silence, crickets chirping response. But gratefully this was not the case. Jim Weirich has a great recap and lists the books we recommend on his blog. The feedback was so positive that we're already cooking up ideas for other talks in this format. To all those who came up and said something to us about our session: Thanks a ton! You have no idea what a help it is to hear from audience members about how it worked or didn't work for them. In short, there's nothing like going out on a limb and having it not break :) Major kudos to Jim and Joe for the idea for this one and for doing a great job pulling it off.

Nathaniel Talbott's hacking session


This was for me the most inspiring session. In a nutshell: hacking is good for you. If it's not fun it's not hacking. Being useful is not the point, enjoying yourself is. It inspired me to hack on rubyjs some more. I had a great time, and managed to come up with something worth sharing I think (tho as I said this was not the point, just a happy accident). More to come.

DHH Keynote

I actually enjoyed this quite a bit. Some of his points I really appreciated: he called BS on the whole IMO messed up american work culture idea that working more and sleeping less makes you supercoderdude. This is total crap, makes us less effective, and it's high time someone said so. Sleep more, and find some hobbies that don't involve computers. Get a life in other words. Great stuff.

Alternative Ruby impls

There was a lot of talk at the conference about non-MRI Ruby interpreters running Rails. I went to the IronRuby session. They run Rails and showed a simple scaffold example working. But I was most impressed by their silverlight demo of ruby running in the browser. Of course, only works in windows and maybe OSX. Allegedly moonlight will catch up. I'd love to really believe MS on that, but I'll believe it when I see it.

I didn't see the Rubinius talk but the did show it running Rails in a keynote. Boy is it slow, but if they can get performance up to snuff it sure is cool to have ruby in ruby.

Maglev IMO got a ton of unwarranted buzz. The part Avi did was cool, but the next part with the gemstone guy ruined it. They are nowhere close to running rails, and the sales guy was casting these sneaky sideways slams of other impls and selling a lot of vaporware. The perf numbers are impressive, but I totally agree with Charles that they mean nothing until they implement all of Ruby. Overall, I thought it kind of FUDDY, and I was quite saddened that the community just went along with it hook line and sinker.

JRuby was there, and had some good talks but since they've been running rails for a long while this wasn't really news and didn't get so much attention. I really like the JRuby rack stuff a lot tho, it opens even more doors. And I had at least one awesome hallway conversation about some big companies adopting JRuby and doing interesting stuff.