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 :)

34 comments:

brainopia said...

This is absolutely cool!

I would definitely like to use something like rubyjs on rails =)

And it will be even more amazing if it will have a support for seamless integration with jquery!

May be something like

J('.some-class').each {|it| it.children().any? &:hidden? }.each do |element|
element.toggle().effect('highlight', {}, 2000)
end

tea42 said...

jQuery interface would be even more useful I think.

I'm still trying to understand the difference between red and rubyjs.

oy said...

WoW shares many wow gold of its features with previously launched games. Essentially, you battle with wow gold cheap monsters and traverse the countryside, by yourself or as a buy cheap wow gold team, find challenging tasks, and go on to higher aoc gold levels as you gain skill and experience. In the course of your journey, you will be gaining new powers that are increased as your skill rating goes up. All the same, in terms of its features and quality, that is a ture stroy for this.WoW is far ahead of all other games of the genre the wow power leveling game undoubtedly is in a league of its own and cheapest wow gold playing it is another experience altogether.

Even though WoW is a Cheap Wow Gold rather complicated game, the controls and interface are done in warhammer gold such a way that you don't feel the complexity. A good feature of the game is that it buy wow items does not put off people with lengthy manuals. The instructions cannot be simpler and the pop up tips can help you start playing the game World Of Warcraft Gold immediately. If on the other hand, you need a detailed manual, the instructions are there for you to access. Buy wow gold in this site,good for you, BUY WOW GOLD.

Game player said...

i can get silkroad gold cheaply,
Yesterday i bought sro gold for my brother.
i hope him like it. i will give silkroad online gold to him
as birthday present. i like the cheap silkroad gold very much.
I usually buy the silk road gold and keep it in my store.
I can getSword of the New World Vischeaply,
Yesterday i boughtSword of the New World Gold for my brother.
i hope him like it. i will give Sword of the New World money to him
as birthday present. i like the cheap snw vis very much.
I usually buy vis and keep it in my store.

said...

You know ,I have some 9Dragons gold, and my friend also has some
9 Dragons gold,do you kouw they have the same meaning,Both of them can be called
9Dragons money,I just want to
buy 9 Dragons gold, because there are many
cheap 9Dragons gold.
You know ,I have some Anarchy credits, and my friend also has some
Anarchy Online credits, do you kouw they have the same meaning,Both of them can be called
Anarchy gold,I just want to
buy AO credits, because there are many cheap
Anarchy online gold.

yanhui said...

Once I played 4story, I did not know how to get strong, someone told me that you must have 4story Luna. He gave me some 4story Gold, he said that I could buy 4story Luna, but I did not have money, then I played it all my spare time. From then on, I got some 4story money, if I did not continue to play it, I can sell cheap 4story Luna to anyone who want.

Once I played stoneage2, I did not know how to get strong, someone told me that you must have stoneage2 Gold. He gave me some stoneage 2 Gold, he said that I could buy stoneage2 money, but I did not have money, then I played it all my spare time. From then on, I got some buy stoneage2 Gold, if I did not continue to play it, I can sell stoneage 2 money to anyone who want.

xiaoqiu said...

buy lindens is the step process and is the required step for our players have to do. I think that it is right and required, because nothing is free and in particular the cheap linden in Second Life game. You do not have to spend second life linden, you can be as solitary as you want to be too. Once you get through the orientation you will be well on your way to exploring the ways of making linden dollars. So instead I am going to give you some secondlife money and the tip of the iceberg.
Rom Gold which I have spent much more in this game it is necessary. Frogster continues to throw the Runes of Magic Gold all the game-play they can possibly find into Runes of Magic. Once the race card is full the race begins, with players avoiding to buy Rom Gold and magical traps. It just amazes me how cheap Runes of Magic Gold and stuff Frogster is tossing into Runes of Magic. Players can help themselves and hinder their foes by picking up Runes of Magic money.

rhtehe said...

Do you know the Archlord gold, in the game you need the Archlord money. it can help you increase your level. My friends always asked me how to buy Archlord gold, and I do not know he spend how much money to buy the archlord online Gold, when I see him in order to play the game and search which the place can buy the
cheap Archlord gold. I am happy with him.
Do you know the 2moons dil, in the game you need the 2moons gold. It can help you increase your level. My friends always asked me how to
buy 2moons dil, and I do not know he spend how much money to buy the
2moon dil, when I see him in order to play the game and search which the place can buy the
cheap 2moons gold. I am happy with him.

fangyan said...

As a new player , you may need some game guides or information to enhance yourself.
wow gold is one of the hardest theme for every class at the beginning . You must have a good way to manage your World of Warcraft Gold.If yor are a lucky guy ,you can earn so many warcraft gold by yourself . But if you are a not , I just find a nice way to buy wow gold. If you need , you can buy cheap wow gold at our website . Go to the related page and check the detailed information .

Making aoc gold is the old question : Honestly there is no fast way to make lots of conan gold . Sadly enough a lot of the people that all of a sudden come to with millions of age of conan gold almost overnight probably duped . Although there are a lot of ways to make lots of cheap aoc gold here I will tell you all of the ways that I know and what I do to buy aoc money.

xw said...

seal cegel and the swordsman in the seal online. Is it solo able in the sealonline cegel? It is not too bad, you should survive pretty well with seal online cegel if you equipment is up to date. Someone would like me who just reached IVI90 be able to survive more than one hit because cheap seal cegel. The work of the reward system works without buy seal online cegel.
silkroad gold in the silkroad you may or may not notice. I know vitality is very tempting in sro gold. You may be feeling intelligence in silk road gold. You are going to be getting crab pincers which like silkroad online gold, depending on which server you are on. cheap silkroad gold can help you get a high level in short time.

wow gold said...

Weekends to peopleig2tmean that they can have a two-day wowgold4europe good rest. For example, people gameusdcan go out to enjoy themselves or get meinwowgoldtogether with relatives and friends to talk with each storeingameother or watch interesting video tapes with the speebiewhole family.
Everyone spends agamegoldweekends in his ownmmoflyway. Within two days,some people can relax themselves by listening to music, reading novels,or watchingogeworld films. Others perhaps are more active by playing basketball,wimming ormmorpgvipdancing. Different people have different gamesavorrelaxations.
I often spend weekends withoggsalemy family or my friends. Sometimes my parents take me on a visit to their old friends. Sometimesgamersell I go to the library to study or borrow some books tommovirtexgain much knowledge. I also go to see various exhibition to broadenrpg tradermy vision. An excursion to seashore or mountain resorts is my favorite way of spending weekends. Weekends are always enjoyable for me.
igxe swagvaultoforu wowgold-usaignmax wowgoldlivebrogame thsaleGoldRockU

milf said...

black mold exposureblack mold symptoms of exposurewrought iron garden gatesiron garden gates find them herefine thin hair hairstylessearch hair styles for fine thin hairnight vision binocularsbuy night vision binocularslipitor reactionslipitor allergic reactionsluxury beach resort in the philippines

afordable beach resorts in the philippineshomeopathy for eczema.baby eczema.save big with great mineral makeup bargainsmineral makeup wholesalersprodam iphone Apple prodam iphone prahacect iphone manualmanual for P 168 iphonefero 52 binocularsnight vision Fero 52 binocularsThe best night vision binoculars here

night vision binoculars bargainsfree photo albums computer programsfree software to make photo albumsfree tax formsprintable tax forms for free craftmatic air bedcraftmatic air bed adjustable info hereboyd air bedboyd night air bed lowest price

milf said...

new houston house houston house txstains removal dyestains removal clothesstains removalteeth whiteningteeth whiteningbright teeth

jennifer grey nosejennifer nose jobscalebrities nose jobsWomen with Big NosesWomen hairstylesBig Nose Women, hairstyles

milf said...

dessicant air dryerpediatric asthmaasthma specialistasthma children specialistcarpet cleaning dallas txcarpet cleaners dallascarpet cleaning dallas

vero beach vacationvero beach vacationsbeach vacation homes veroms beach vacationsms beach vacationms beach condosmaui beach vacationmaui beach vacationsmaui beach clubbeach vacationsyour beach vacationscheap beach vacations

bob hairstylebob haircutsbob layeredpob hairstylebobbedclassic bobCare for Curly HairTips for Curly Haircurly hair12r 22.5 best pricetires truck bustires 12r 22.5

washington new housenew house houstonnew house san antonionew house ventura

milf said...

find air beds in wisconsinbest air beds in wisconsincloud air beds

best cloud inflatable air bedssealy air beds portableportables air bedsrv luggage racksaluminum made rv luggage racksair bed raisedbest form raised air bedsbed air informercialsbest informercials bed airmattress sized air beds

bestair bed mattress antique doorknobsantique doorknob identification tipsdvd player troubleshootingtroubleshooting with the dvd playerflat panel television lcd vs plasmaflat panel lcd television versus plasma pic the bestadjustable bed air foam The best bed air foam

hoof prints antique equestrian printsantique hoof prints equestrian printsBuy air bedadjustablebuy the best adjustable air bedsair beds canadian storesCanadian stores for air beds

migraine causemigraine treatments floridaflorida headache clinicdrying dessicantair drying dessicant

beautyli said...

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . I like it

beautyli said...

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . I like it

beautyli said...

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . .. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . good,very good!

beautyli said...

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . . .

This article is very good,I like it !

beautyli said...

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . good!good!

lady said...

I like the side of the article, and very like your blog, to write well and hope to continue their efforts, we can see more of your articles. ed hardy clothes. After reading this article has strong feelings, the future will be ed hardy womens longsleeve.ed hardy longsleeve
ed hardy hoodies
ed hardy jeans
ed hardy
ed hardy clothing
ed hardy t-shirts
cheap ed hardy clothing
ed-hardy.co.uk
ed hardy shirts
wholesale ed hardy clothing
ed hardy outerwear
ed hardy mens outerwear
ed hardy womens outerwear
ed hardy clothes
ed hardy boots
ed hardy outerwear
ed hardy hoodies
ed hardy Jeans
ed hardy hoodies
ed hardy jackets
ed hardy womens jackets
ed hardy mens jackets
ed hardy bags
ed hardy trousers
ed hardy shoes
ed hardy longsleeve
ed hardy mens longsleeve
ed hardy womens longsleeve
ed hardy jackets
ed hardy suits
ed hardy clothing
ed hardy shoes
ed hardy jeans
ed hardy boots
ed hardy mens sweater
ed hardy womens cotton
ed hardy womens boots
ed hardy
ed hardy womens clothing

Nguyen Manh said...

池袋 風俗
渋谷 風俗
新宿 風俗
コンドーム 激安
アダルトDVD
av 写真
アダルトグッズ
アダルトグッズ
アダルトDVD
アダルトショップ
ペニス増大
電マ
TENGA
SM 通販
セクシー下着
男性下着
Tバック下着
大規模修繕
決済代行
SEO
SEO
fether felt flat
決済代行
ブライダルエステ
FX 比較
クレジットカード 申込
子猫
子犬
仔猫
アダルトショップ
アダルトグッツ
ゴールドカード ランキング
調査料金 探偵
行動調査 探偵

Nguyen Manh said...

夫の浮気調査 探偵
身元調査 探偵
所在調査 探偵
浮気調査
ストーカー調査
素行調査
盗聴調査
身元調査
不倫調査
不倫調査
尾行調査
企業調査
身元調査
身辺調査
夫の浮気 相談
浮気 相談
身上調査 相談
所在調査 相談
不倫調査 相談
盗聴調査 相談
結婚詐欺 相談
ダッチワイフ
ビジネス英会話
ビジネススクール 英語

Adi said...

Oes Tsetnoc one of the ways in which we can learn seo besides Mengembalikan Jati Diri Bangsa. By participating in the Oes Tsetnoc or Mengembalikan Jati Diri Bangsa we can improve our seo skills. To find more information about Oest Tsetnoc please visit my Oes Tsetnoc pages. And to find more information about Mengembalikan Jati Diri Bangsa please visit my Mengembalikan Jati Diri Bangsa pages. Thank you So much.
Oes Tsetnoc | Semangat Mengembalikan Jati Diri Bangsa

qingchengzhilian said...

Your blog is very good, it's the best blog I've ever seen, thank you!
By the way, do you like polo shirts, which are very chic, especially the polo t shirts, I love them very much. I also like playing tennis rackets, it can keep healthy, what do you like to do?
polo t shirts women
polo t shirts on sale
polo t shirts for women
polo shirts on sale
polo shirts men
men's polo shirt
men polo shirt
mens polo shirts
mens polo shirt
cheap polo shirts
discount polo shirts
men's polo shirts
women's polo shirts
cheap tennis racket
discount tennis racket
prince tennis racquet
head tennis rackets
wilson tennis racket
babolat tennis racquet

liu said...

Your blog is so excellent that I like it very much, you must be good at writing. And what do you think of cheap polo men t shirts, I think they are are very chic, especially the cheap polo t shirts, I love them very much.
polo t shirts
discount polo t shirts
polo t shirts on sale
polo t shirts cheap
cheap polo mens shirts
polo t shirts women
polo t shirts for women
polo shirts on sale
discount polo shirts
men's polo t shirt
polo men t shirts

aiya said...

Office 2010is powerful!
Microsoft Office 2010is the best software in the world.
Microsoft wordis so great!
Office 2007makes life great!
Many people likeMicrosoft Office.
Microsoft Office 2007is welcomed by the whole world.
Office 2007 keyis available here.
Office 2007 downloadis on sale now!
Office 2007 Professionalbring me so much convenience.
Outlook 2010 make life wonderful!
Microsoft outlook is my love.
Microsoft outlook 2010 is convenient!
Windows 7 is convenient!

Albert H. said...

What the hell?

teramoney said...

http://www.tera2u.com/news/detial/The-role-of-tera-class-up-to-58

http://www.wowbotsfree.com/some-current-popular-ways-of-online-games-charging/

http://www.dnfonlines.com/a-classification-of-online-games-charging/

liuyunxin said...

I really enjoy your posts as I learn a lot from them. I also broaden my thinking as far as what I can use and do with thingsHere useful link:
diablo 3 gold
guild wars 2 gold
guild wars 2 gold
diablo 3 gold
diablo 3 gold
guild wars 2 gold
tera gold
diablo 3 gold
guild wars 2 gold
guild wars 2 gold
diablo 3 gold
diablo 3 gold
guild wars 2 gold
tera gold

xinag zhong said...

As well asBuy rs gold the earlier hen price makes it the top seminar offer That i've ever been aware of. Daylights, including the publish first bird pace causes it to become the very best conference bargain That i've ever heard of. Therefore enroll currently. Cheapest Diablo 3 goldYou already know you actually want to.

AntoL-Nyo said...

HD kaliteli porno izle ve boşal.
Bayan porno izleme sitesi.
Bedava ve ücretsiz porno izle size gelsin.
Liseli kızların ve Türbanlı ateşli hatunların sikiş filmlerini izle.
Siyah karanlık odada porno yapan evli çift.
harika Duvar Kağıtları bunlar
tamamen ithal duvar kağıdı olanlar var

AntoL-Nyo said...

Ben istanbuldan selda 22 yaşında konfeksiyon içşisiyim Amatör Porno sizleri bekletmeden hemen hikayeme geçiyorum.. Biz 5 katlı bir binanın en üst katında yaşıyorduk ve bir öğlen paydosunda sevgilim beni Anal Sikiş aradı evdeydim çünkü evle iş yerim arasında 2 dakika bile yoktu.. Bende Asyalı Porno sevgilime benden telefon beklemesini söyledikten sonra evin durumuna baktım evde kardeşlerim ve annemin Esmer Porno birkaçtane arkadaşı vardı bu iş imkansızdı tekrardan düşündüm ve çatı katı aklıma geldi sevgilime telefon açıp çatıya çıkmasını ve Fantazi Porno beni beklemesini söyledikten sonra telefonu bir süre elime almadım anneme işe gidiyorum dedikten sonra Gay Porno hemen üst kata çatıya çıkıp sevgilimin
dudaklarına yumuldum az bir süremiz Götten Sikiş vardı ve çok istiyordum onu hemen önünde diz çöküp sikini çıkardım kocaman olmuştu bile... Özlemişti beni HD Porno bitanem başladım sikini yalamaya kafasını öpüyor onu çıldırtıyordum sevgilim saçlarımdan tutmuş ağzımı keyifle sikerken çatı katının kapısı açıldı toparlanamadan Lezbiyen Porno komşunun şişman oğlu efecan gelmişti ben dizlerimin üzerinde sevgilimin Liseli Porno siki ağzımda yakalanmıştım hemen bu halimizi gören komşu oğlu Sarışın Sikiş kaçarcasına gitti.. Sevgilim bir süre güldükten Türbanlı Porno sonra bu şişko neden kaçtı korktu herhalde onu sikicem sandı galiba dedikten sonra bir kahkaha daha attı ben sevgilimin Türk Porno sikine deli gibi saldırıyor yalıyor emiyordum boşalmasını istiyor Zenci Porno sütünü içmek istiyordum sevgilim ağzımı sike sike boşaldı hepsini yuttum bir damlasını ziyan Porno etmedim ve sevgilimle vedalaşıp ayrıldık... Ben her defasında sikiş yapmadan önce yazporno diye olan türkçe siteden Porno izle bölümüne girip seyrediyorum azdıktan sonra şahane sikiş ile gözleri kamaştırıyorum.

prathap kumar said...

JavaScript Training Course is essential to the achievements of an individual. Perhaps its most positive benefit is better employees. A company develop the potential of an employee, and part of the way a company encourages improvement is through training.

JavaScript Course
Online Javascript Course
Javascript Course Online
Free Online Javascript Course

AngularJS Interview Questions
JavaScript Tutorials