Subscribe to my Feed, follow me on Twitter, recommend me on Working With Rails or see my code on GitHub
Unobtrusive Ajax patterns: the remote form
I’ve decided to adapt a more “stream of consciousness” style of writing, because my yearning for perfection has so far only resulted in lots of posts that never get finished or even started. Yeah, no such thing as perfection.. Who would’ve thought? This is the first in what may become a series of posts showing how you can apply common Ajax or JavaScript patterns unobtrusively to your HTML.
A “remote form” is a form which submits asynchronously and acts upon the response. To make a normal form “remote”, stop the “submit” event and send off an Ajax request.
The form, with a “remote” class to identify it (and others!):
<form action="/articles" class="remote" method="post">
<input id="article_title" name="article[title]" />
<textarea id="article_body" name="article[body]"></textarea>
<input type="submit" value="Save" />
</form>
The JavaScript finds all forms with the “remote” class and hijacks them so that they’re submitted asynchronously:
document.observe('dom:loaded', function(){
$$('form.remote').each(function(form){
form.observe('submit', function(e){
e.stop(); //Stop the default action, which is to submit the form the normal way
form.addClassName('enhanced');
form.request({
onComplete: function(res){
doSomethingWith(res.responseText);
}
});
});
});
});
You could add a “link” class to have the form replaced with a link:
<form action="/articles" class="remote link" method="post">
<!- ... ->
</form>
document.observe('dom:loaded', function(){
$$('form.remote').each(function(form){
if (form.hasClassName('link') {//Replace with a link
var link = new Element('a', {href:'#'})
//Use the value of the submit button as the value for the link
link.update(form.down('input[type=submit]'));
//When the link is clicked, it should submit the form
//The form will catch the submit event and submit asynchronously
link.observe('click', function(e){ e.stop(); form.submit(); });
//Insert the link _after_ the form
form.insert({after:link});
}
form.observe('submit', function(e){
/* Same as above. The form will catch the submit event fired
by the link and submit asynchronously */
});
});
});
Note that nothing is done to the form in the case where it has the “link” class name. The form receives the “enhanced” class name regardless of if it’s a link or not, and with that we can target it with CSS and hide the form:
form.remote.enhanced.link {
display: none;
}
How to create a Twitter widget/client with unobtrusive, degradable JavaScript and FakeJAX
In this post I’ll go through adding a Twitter widget to a web page unobtrusively with JavaScript. The Twitter aspect of it is not really what I’m trying to show; it just makes it a bit more interesting I guess, and is something I thought of after I wrote a Twitter client to learn XUL. There are three main reasons I wanted to write this:
- I wanted to show that using JavaScript in an unobtrusive style is far from being a chore and actually makes things a lot easier, organised and scalable,
- to show how incredibly helpful it is to know and love JavaScript (I used to bang on it until it sort of worked, and that took much longer and was so frustrating) when developing dynamic web pages,
- and to showcase something I’ve been working on ;)
The rest of the article and a working widget example after the jump..
Barby 0.1.1
Update: Just released 0.1.2, which includes a CairoOutputter written by Kouhei Sutou. It uses Cairo to generate SVG, PDF, PS and PNG.
I just released a minor update to the Barby gem. It’ll probably take a few hours before it’s available from the gem servers, but you can always get it from GitHub
The release includes some minor fixes and a new outputter class which uses the “png” gem (can’t find any description of it on the internets, but you can install it with gem install png).
You can use the new outputter just by requiring the file. It will register the to_png method like RmagickOutputter.
require 'barby'
require 'barby/outputter/png_outputter'
puts Barby::Code128B.new('HUMBABA').to_png
It’s not really much faster than RMagick, but I guess some people will prefer it as it’s more lightweight and doesn’t leak memory like RMagick does ;)
Moved plugins to git
I’ve moved all of my plugins to Github:
Ok, by “all plugins” I actually mean “all useful plugins”. There are a few that won’t be moved to Git because they suck and I thought this would be a good opportunity to neglect them and let them slowly fade away into nothingness. The lucky few to receive a free trip to the plugin underworld are:
- ActsAsSluggable, which is useless now
- RestfulXHTML, because it doesn’t work well and I’ve kind of given up on making it work and become “pragmatic” :/
- ValidatesCaptcha, because CAPTCHAs are evil
All of these will still be available from their Subversion repos.
Ready to take my clothes off
April 9 is CSS Naked Day. Here’s a simple Rails helper that determines if Time.now is naked day:
def naked_day?(day=9, month=4)
start = Time.utc(Time.now.year, month, day) - 12.hours
stop = Time.utc(Time.now.year, month, day) + 36.hours
now = Time.now.utc
now > start && now < stop
end
(Naked day lasts for 48 hours, 24 + 1 hour for each timezone)
Put it in application_helper.rb, and you can use it in your layout like this:
<head>
<% unless naked_day? -%>
<%= stylesheet_link_tag 'application' %>
<% end -%>
</head>
Introducing Barby
Everyone, please say hello to Barby. She’s really into barcodes.

Barby was born out of frustration with the lack of a decent Ruby library for generating barcodes. There are a few of them out there, but they’re either very sparse on documentation and structure, probably having been made for a very specific purpose, or they depend on GNU Barcode. I was using gbarcode for Ruby until I hit a case where it couldn’t do what I needed it to. My choice then was to either try and shoehorn it into doing what I wanted or create my own. With my C-fu being as good as non-existent, I chose the latter and created Barby, which I like to think is a younger, more persuadable and flexible barcode generator.
Barby has support for several commonly used barcode symbologies, and is easily extended. The current list is:
- Code128
- GS1128 (aka EAN/UCC-128)
- EAN-13 (aka UPC-A)
- Bookland
- EAN-8
- Code39
You can add support for more by subclassing Barby::Barcode. The only requirement is that is has an encoding method which returns a string representation of the barcode consisting of 1s and 0s, 1 being a “bar” and 0 “space”. This encoding is used when creating graphical or other representations of the barcode. This process is separated into “outputters”, so you can easily add new ones. For example, the image above was created with the RMagickOutputter using the following code:
require 'barby'
require 'barby/outputter/rmagick_outputter'
barcode = Barby::Code128B.new('IM-IN-UR-BARCODE')
File.open('test.png', 'w') do |f|
f.write barcode.to_png
end
The outputter classes included right now are RMagickOutputter, PDFWriterOutputter and ASCIIOutputter. These need to be required before use, as some might have “heavy” dependencies such as RMagick.
To install,
gem install barby
Barby lives in the Github Dream House. API docs can be found at Rubyforge.
Unobtrusive JavaScript with Rails
Just finished an article about writing unobtrusive JavaScript with Rails. The title is a bit misleading, as it’s not that much about Rails, and it’s not about writing unobtrusive JS per se. It’s more about how to structure the JavaScript and create reusable code and encapsulated elements from the HTML contents that know how to do things on their own and are aware of their context. That last sentence probably came out as “blah-blah-oh-look-at-me-i’m-so-clever-blah-blah”, but it’s actually pretty simple and very useful; trust me ;)
Jibberish
http://nimrod.interinter.net/plugins/trunk/jibberish/
This is something I created a few weeks ago but didn’t tell anyone about yet. I recently used (something like) it on a client application, and it’s been working really well, so I thought I’d share it with the world. It’s a plugin for Gibberish (yes, that’s a plugin to a plugin) which takes all the defined translations, exports them to JavaScript and adds a few convenience methods.
Why would anyone need this? Well, let’s say you’re building a Multilingual Web 2.0 App With Lots Of Ajax (MWTAWLOA). You use the delightfully simple Gibberish to translate all the strings in your MWTA, and all is well. After a while, you start to layer all the Ajax functionality on top of your (already functioning) application, the way God intended. But wait, what about all those strings in your JavaScript? How will your Elbonian users understand what you’re trying to say? You could create different JS files for each language, and let the server decide which one gets used, but that results in a lot of duplication and WETness. Or you could create a separate translation system for the client side of things (which is very easy), but again this results in duplication. What you should do, of course, is reuse the translations already present on the server on the client.
So, how do you use Jibberish? First of all, you must be using Gibberish, as Jibberish is meaningless without it. Then, after installing the plugin from Github, include the JavaScript file in your layout
<!-- ... -->
<head>
<title>My multilingual Rails app</title>
<script src="/javascripts/jibberish.js"></script>
</head>
<!-- ... -->
And access the translations through the Jibberish object:
Jibberish.locales //=> {es: {...}, no: {...}}
Jibberish.locales.es.hello //=> "Hola"
If you set a “locale” cookie containing the language code of the current language..
def set_locale
Gibberish.current_language = 'es'
cookies['locale'] = 'es'
end
..things get even easier:
Jibberish.currentLanguage //=> "es"
Jibberish.get('order_beer') //=> "Una cerveza, por favor"
The “locale” cookie will be picked up automatically, but you can set the current language on the client as well:
Jibberish.currentLanguage = 'no'
Jibberish.get('order_beer') //=> "Gi mæ en øll"
It even has a convenient String method, like Gibberish:
"Good evening".t('good_evening')//=> "Buenas tardes"
//It has default key handling like Gibberish
"I have fish in my pants".t() //=> "Æ har fesk i boksa"
//The key will override the contents of the string
"My pants are fish-free".t('i_have_fish_in_my_pants') //=> "Æ har fesk i boksa"
A singleton function?
This function allows you to make sure a function gets run only once. I’ve been trying to come up with a better name for it than singletonize, because it doesn’t really have anything to do with singletons. I’m thinking that people before me must have done the same thing and come up with a better name. Is this a common pattern, and what is it called?
Function.prototype.singletonize = function(){
var fn = this,
hasRun = false;
return function(){
if (!hasRun) {
hasRun = true;
return fn.apply(this, arguments);
}
};
}
Usage:
var o = {
foo: 'bar',
bar: (function(){
print(this.foo);
}).singletonize()
};
o.bar(); //prints "bar"
o.bar(); //does nothing
Unicode is fun
There are lots of nifty things you can do once you have access to all the world’s different alphabets and scripts:
λ{ (√ ∑((Ⅿ * (١ ٧ ٨ ٧)), (Ⅾ Ⅼ Ⅹ Ⅴ Ⅰ Ⅰ Ⅰ Ⅰ))).floor }.❪❫
#=> 1337
(You might not have the right fonts in order to see everything above, in which case you’ll probably see lots of squares or question marks. Oh, and I’m not sure it will work in Ruby 1.9 because it’s missing quite a few parentheses)
But is it useful? Probably not. Unless you made your own keyboard with all the characters you want, instead of the basic n00b Latin set they force upon us. The point is, Unicode is awesome and no-one should be using anything else, ever.
