Posted 3 years ago

HTML 5 Review

For a looong time there hasn’t been any development of the HTML standard. HTML 4 was released in December 1997, with few minor updates since then. Finally in recent years a lot of people realised that the current HTML 4 standard isn’t enough for needs of the modern web development and since the situation in W3C has been complicated, the Web Hypertext Application Technology Working Group ( WHATWG) started to work on a new standard …

From People-Friendliness to Machine-Friendliness

Do you remember when every single page on the internet had at least one <marquee> tag and a bunch of others like <font>? It worked, but these HTML pages had been useless for extracting informations like events, contacts or just simply determining which part of the page is important and which contains just style or copyright information for example.

And then the semantic web comes to help to sort out the situation. One of the important standards which builds on the idea are microformats, Resource Description Framework (RDF) and – yeah you guess it – HTML 5. Let’s take a look at these semantic elements:

  • <nav>
  • <section>
  • <article>
  • <aside>
  • <hgroup>
  • <header>
  • <footer>
  • <time>
  • <mark>

It’s quite obvious what (most) of the elements are good for. Let’s take a look at an example:

<!-- This is how the doctype in HTML 5 looks like, note how much simpler it is -->
<!DOCTYPE html>
<html>
  <head>
    <title>HTML 5 Example</title>
    <!-- handy shortcut for declaring encoding -->
    <meta charset="utf-8">

    <!-- type attribute at links to CSS isn't required anymore -->
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
    <nav>
      <ul>
        <li>About</li>
        <li>Posts</li>
      </ul>
    </nav>

    <h1>Posts</h1>

    <article>
      <h1>Title</h1>
      <p><time datetime="2010-04-15" pubdate>last Thursday</time></p>
      <p>Lorem ipsum dolor sit amet ...</p>
    </article>

    <!-- pagination, you can use new attributes for rel -->
    <a href="?page=1" rel="first">1</a>
    <a href="?page=2" rel="prev">2</a>
    3 <!-- current page -->
    <a href="?page=4"rel="next">4</a>

    <footer>© Jakub Stastny 2010</footer>
  </body>
</html>

You can try to validate the example in HTML 5 validator.

Interesting thing is that you can use h1 for article titles. Of course, you can do it in HTML 4 as well, but the difference is that in HTML 5 it doesn’t break the document outline. So you can simply put this snippet within the article tag anywhere into your page without any modifications. If you want to check if your document outline make sense, you can use HTML 5 outliner.

Furthermore, it’s important for other software like HTML readers for disabled users: nowadays they simply can’t recognize what is navigation and what is main content, what is next page and what the previous one etc.

You can read more about semantic HTML element at DiveIntoHTML.org.

Forms

Forms in HTML 5 introduce a lot of new types, which are all backwards compatible with plain old text fields, for example:

  • email
  • url
  • number with additional min, max and step
  • color
  • date, month, week, time, datetime, datetime-local

Now you migth be wondering what is it actually good for? Indeed, color or date will be represented as a color or date picker, but what about url or email - doesn’t the email field looks exactly the same as a normal text field? It does, but it’s easier for browsers to fill in the form if they know what is expected, and on your iPhone you get a different keyboard for url or email so it’s easier to write them. And of course browsers can do validations, so you don’t have to do it yourself (at least in the client-side code, you should always do validations on server). Finally they come with some JavaScript API, so for example you can use input.stepUp(n), input.stepDown(n) or input.valueAsNumber on numbered inputs.

There are also two new interesting attributes of the input tag: placeholder and autofocus. Placeholder is just a text which disapears when you click to the field: usually it’s a hint about what a given field expects to get (e.g <input placeholder=”Your name”>.)

When you have autofocus at an input, it’ll be active, so you can immediately write in there. Just use <input autofocus>, that’s it.

Read more about HTML 5 forms at DiveIntoHTML.org.

Videos & Audios

It’s a shame that the current HTML standard doesn’t have any kind of support for video and audio, which has become increasingly common. Consider all the websites which have to use flash in order to get video working. Not to mention how many people, including myself, who don’t like flash: I don’t want flash to eat half of my CPU or even crash my browser. But I had to use it if I wanted to view videos on YouTube and similar sites. Many sites, including YouTube are now starting to support HTML 5’s video standard.

Nowadays there is support for <video> in most of the modern browsers, but the trouble is with the codecs used to store the video. The Open Source community wants to use the patent-free Theora codec, however some others, like Apple prefer H.264. A similar situation seems to occur reguarding theaudio codecs. The H.264 standard does have a much better compression compared to Theora, however does have licensing problems.

Read more about HTML 5 videos at DiveIntoHTML.org.

WebSockets

For me, WebSockets are one of the best parts of HTML 5. The principle is dead-simple: it’s just a socket (a persistent, two way connection between browser and server), but built-in your web page. Forget long-polling via Comet, WebSockets are the future. Well, the future, but you can use them today, as there is a fallback flash implementation for browsers which don’t support them natively yet.

Especially for us in Headshift, WebSockets can be really useful, I believe. Social software can have a lot of forms, but the trend is obvious: we are moving from less interactive software to more interactive applications and even real-time communication. And this is what WebSockets are really about. Imagine for example how WebSockets can improve development and the user experience of such applications as Google Wave, Pivotal Tracker or basically all the collaborative tools.

You should definitely take a look at the video at PusherApp.com, it explains a lot.

Canvas

Most developers have heard of or even used Canvas. It’s useful for doing graphics in your HTML using JavaScript. Nothing really new, considering SVG which can be embedded into HTML pages and even scripted in a similar way. However, the main difference is that SVG was never consistently implemented in modern browsers. There is some support, but in general, you don’t want to use SVG on web. Which is a shame, considering it is a nice format. The reason is simple: SVG is really complex and since canvas is much simpler it has a much better chance.

Geolocation

More and more people have smart mobile devices. Notebooks, netbooks, iPhone, iPad, Android phones … and geolocation is getting really important part of applications. But actually not just for applications, it can be really useful even for simple web presentations. If you are looking for a pub nearby, the search engine can use your location to know where the “nearby” is. And furthermore the pub can have on their site something like “show me how to get there”.

But don’t worry, big brother can’t follow you unless you give him explicit permission to do so. For example in Firefox you get the same bar as the one which ask you if you want to save your password and only if you say “yes, this page can use my location”, then the browser gives it.

Local Storage

This is another HUGE awesomness of HTML 5. In short, it’s just a SQLite3 database in browser which you can use from your web page. Or more likely from your web application, so your e-mail application can works offline, as well as your online task manager etc. Obviously it won’t actually send e-mail when you are offline, but it can save them and send them later, you can still create and edit drafts, use search … and all this stuff. Local storage turns “dumb” HTML & JS into a proper application semi-independent from network connectivity issues!

Using HTML 5 Today

According to HTML 5 validator, headshift.com have only 5 problems to become HTML 5 valid! Of course it doesn’t use any of HTML 5 goodnesses, but still, it means that converting your pages into HTML 5 compatible will be fairly easy.

A good thing about HTML is that it’s very fault-tolerant. So if you use some elements which your browser doesn’t know, it just doesn’t matter, it will work anyway. Well it won’t do anything special, but it doesn’t fail and it’s important. Because if browser doesn’t support a given feature, you can detect it (for example via Modernizr) and write your fallback solution in JavaScript. It’s so simple!

Or to be precise it would be so simple if Internet Explorer doesn’t exist (jeez, it would be so awesome!) Unfortunatelly it does and as usual it breaks things. The issue is that IE doesn’t support styling on unknown elements and it doesn’t parse the DOM properly. So if we have:

<article>
  <h1>My New Post</h1>
  <p>Lorem ipsum dolor sit amet ...</p>
</article>

All the reasonable browsers will create the tree [{article: [h1, p]}], but Internet Explorer creates [article, h1, p]. Unbelievable! Fortunatelly there is a fix for this misbehaviour.

iPad & iPhone Applications

Since we aren’t currently developing any iPhone or iPad application, I’m not going much into details here, but I think it’s worth to mention it anyway: It’s really easy to develop a mobile application in HTML 5. Consider all these cool technologies like geolocation or local storage! If you are interested, I can recommend you to take a look at How to Make an HTML5 iPhone App and the Apple Safari Development Reference.

Sources

Posted 3 years ago

DRY Your YAML Files!

It’s basically a simple inheritance pattern in YAML:

development: &defaults
  adapter: mysql
  encoding: utf8
  database: acme_development
  username: root

test:
  <<: *defaults
  database: acme_test

cucumber:
  <<: *defaults
  database: acme_cucumber

It’s quite obvious what it does: you create a hash development which you assign to the defaults variable and then reuse it and rewrite just keys which are different. So the result is:

require 'yaml'
require 'pp'

pp YAML::load_file("config/database.yml")
{"development" => 
  {"encoding" => "utf8",
   "username" => "root",
   "adapter" => "mysql",
   "database" => "acme_development"},
 "cucumber" => 
  {"encoding" => "utf8",
   "adapter" => "mysql",
   "username" => "root",
   "database" => "acme_cucumber"},
 "test" => 
  {"encoding" => "utf8",
   "adapter" => "mysql",
   "username" => "root",
   "database" => "acme_test"}}

Nice one, isn’t it?

Posted 3 years ago

Mixins in JavaScript

Thanks to JavaScript flexibility it’s incredibly easy to use mixins:

var sys = require("sys");

var extend = function extend (another) {
  var prototype = this.__proto__;
  this.__proto__ = another;
  another.__proto__ = prototype;
  return this;
};

Object.defineProperty(Object.prototype, "extend", {value: extend });

var Model = new Function();

var SQLFindersMixin = {
  findBySQL: function (query) {
    sys.puts("Finding by SQL: " + query);
  }
};

Model.prototype.extend(SQLFindersMixin);

var instance = new Model();
instance.findBySQL("SELECT * from POSTS");

So how does it work? Well we simply inject another item into the prototype chain, so instead of Model.prototype -> Object.prototype we turn it into Model.prototype -> SQLFindersMixin -> Object.prototype. Easy and useful.

Posted 3 years ago

Extending JS Prototypes in Non-Invasive Way

The most serious reason for not extending prototypes of things like Object or Array is that you’ll break iterations. For example

var sys = require("sys");

// let's write the extend function
var extend = function extend (another) {
  var properties = Object.keys(another);
  var object = this;
  properties.forEach(function (property) {
    object[property] = another[property];
  });
  return object;
};

// add it to the Object.prototype
Object.prototype.extend = extend;

// objects initialization
var object  = {name: "Jakub"};
var another = {surname: "Stastny"};

// and let's check iterate over its properties
for (property in object) {
  sys.puts(property)
};

// output
// => name
// => surname
// => extend

Very annoying. Fortunately JavaScript 1.9.3 introduced function Object.defineProperty which gives us higher control and mainly can hide the property for iterators.

Object.defineProperty(Object.prototype, "extend", {value: extend });

for (property in object) {
  sys.puts(property)
};

// output
// => name
// => surname

And that’s it! Obviously you can’t use it in browsers so far, but it works in Node.js so now, I can’t see any serious reason why not to extend Object.prototype when it makes sense. But obviously it has to be done really carefully.

Oh and BTW there is also Object.defineProperties when you need to define more properties at once.

PS: the extend function could use prototype inheritance like this:

var extend = function extend (another) {
  var prototype = this.__proto__;
  this.__proto__ = another;
  another.__proto__ = prototype;
  return this;
};

It’s certainly better for object.extend(mixin), but if you want to merge two objects, it’s better just to copy these properties.

Posted 3 years ago

WSGI & Django Applications on Passenger

Quite cool thing I discovered recently is that you can deploy WSGI applications (Django etc) on Passenger. There is an example app for WSGI out there. Similarly as in Ruby, you have config.ru passenger_wsgi.py which looks like this (it’s a slightly modified version of the linked example):

def application(environ, start_response):
  start_response('200 OK', [('Content-type', 'text/html'), ('X-Foo', 'bar')])
  return ['Hello World!']

And because Django have a WSGI handler, we can simply do something like (I took it from post Serve Django Projects with Phusion Passenger):

import os, sys
sys.path.append('/path/to/your/DjangoProjects')
os.environ['DJANGO_SETTINGS_MODULE'] = 'example_com.settings'

import django.core.handlers.wsgi

application = django.core.handlers.wsgi.WSGIHandler()

Add vhost for the application and you’re done!

Posted 3 years ago

Prototype inheritance in JavaScript II

This article is an continuation of the Prototype Inheritance in JavaScript where I explained what is prototype and how the basics of prototype inheritance in JavaScript works. Today I’ll go on with the new keyword and how to use the more advanced OOP techniques as super() etc.

Many people are confused by OOP in JavaScript, namely by inheritance. There isn’t any standard way how inherit classes in CommonJS standard or anywhere else, so each framework use its own solution.

There are many solutions which are trying to implement classical inheritance (i. JS.Class, Class implementation in MooTools framework, Base.js and much more). I personally don’t like it, but I understand why people do this kind of stuff.

Inheritance in JavaScript

The new Keyword

Here comes a very important “aha” moment – new just creates a new object and assign  object.__proto__ to constructor.prototype. Easy-peasy, right?

var Model = new Function;
Model.prototype.database = {};

var task = new Model;
task.__proto__;
// { database: {} }

So for inheriting instance methods you just needs to assign inheritedClass.prototype to superClass.prototype:

var sys = require("sys");

var Model = new Function;
var Post  = new Function;

Post.prototype = Model.prototype;

Model.prototype.save = function () {
  sys.puts("Saving ...")
};

var post = new Post;
post.save(); // => "Saving ..."

This will work, however when we’ll add a new method into Post.prototype, it’ll be added into Model.prototype as well since both points to the same object. So let’s fix that:

var Model = new Function;
var Post  = new Function;

Post.prototype = new Model;

Model.prototype.save = function () {
  sys.puts("Saving ...")
};

var post = new Post;
post.save(); // => "Saving ..."

This works as well, but what if we initialize some instance-related data in the constructor, i. e. this.key? We don’t want to propagate this mess into our prototype. Not mention if the constuctor takes some init data. So let’s fix that as well:

var Model = function () {
  this.data = [];
};

var Post = new Function;

var temp = new Function;
temp.prototype = Model.prototype;
Post.prototype = new temp();

Model.prototype.save = function () {
  sys.puts("Saving ...")
};

var post = new Post;
post.save(); // => "Saving ..."
sys.puts(sys.inspect(Post.prototype)) // {}

That’s finally better, but it’s quite a lot of type because of such a simple thing as inheritance. Fortunatelly Node.js provides sys.inherits which is doing pretty much the same as we are doing now, so let’s refactor our code:

var Model = new Function;
var Post  = new Function;

sys.inherits(Post, Model);

Model.prototype.save = function () {
  sys.puts("Saving ...")
  return true;
};

var post = new Post;
post.save(); // => "Saving ..."

Cool. Let’s take a look how to extend methods in subclasses. According to John Resig it should be something like:

var Model = new Function;
var Post  = new Function;

Model.prototype.save = function(type){
  sys.puts("Saving ...");
  return true;
}

Post.prototype = new Model();

Post.prototype.save = function () {
  sys.puts("In the Post.prototype");
  return Object.getPrototypeOf(this).save();
};

var post = new Post();
post.save()

// In the Post.prototype
// In the Post.prototype
// Saving ...

This works, but as you can see the function is called twice, because for the first time Object.getPrototypeOf(this) returns Post.prototype. Fortunately the solution is easy:

Post.prototype.save = function () {
  sys.puts("In the Post.prototype");
  var prototype = Object.getPrototypeOf;
  return prototype(prototype(this)).save();
};

// In the Post.prototype
// Saving ...

Or there is another way how to do the same in Node.js:

var Model = new Function;
var Post  = new Function;

Model.prototype.save = function(type){
  sys.puts("Saving ...");
  return true;
}

sys.inherits(Post, Model);

Post.prototype.save = function () {
  sys.puts("In the Post.prototype");
  return this.constructor.super_.prototype.save();
};

var post = new Post();
post.save()

Also, if you want to use some instance variables, you need to do this.constructor.super_.prototype.save.call(this) which will evaluate the method in this which is the current instance.

Inheriting Static Methods

This is the tricky part, because static methods are just properties of the constructor, so they aren’t in its prototype. Which means you have to do it manually, but I think you shouldn’t need it anyway.

Posted 3 years ago

Subdomains in Django: An Example

Writing the middleware

In Django Middleware is a class which respond to one of these methods: process_request, process_view, process_response or process_exception. For more informations see the Django middleware docs.

What we need is just use blog/urls.py on blog subdomain instead of main urls.py. It’s easy, we just need to rewrite settings.ROOT_URLCONF to proper file:

from django.conf import settings
import re

class SubdomainsMiddleware:
    def process_request(self, request):
        request.domain = request.META['HTTP_HOST']
        request.subdomain = ''
        parts = request.domain.split('.')

        # blog.101ideas.cz or blog.localhost:8000
        if len(parts) == 3 or (re.match("^localhost", parts[-1]) and len(parts) == 2):
            request.subdomain = parts[0]
            request.domain = '.'.join(parts[1:])

        # set the right urlconf
        if request.subdomain == 'blog':
            settings.ROOT_URLCONF = 'blog.urls'
        else:
            settings.ROOT_URLCONF = 'web.urls'

We have also added domain and subdomain properties to the request object, so we can access to these variables in your views.

Get it working

DNS

First you should ensure that all the subdomains are routed to server where your application runs. It should look like this:

* CNAME 101ideas.cz

Apache

ServerAlias blog.101ideas.cz

Of course if you like to route all the subdomains to your application, then use the wilcard. For example ServerAlias *.101ideas.cz.

Django

We need to register the middleware in settings.py:

import middleware

MIDDLEWARE_CLASSES = ('middleware.SubdomainsMiddleware',)

Localhost settings for development

First you must add this line to your /etc/hosts:

127.0.0.1 blog.localhost

It should works immediately. Just start ./manage.py runserver and try to go to http://blog.localhost:8000/.

Cookies

If you want to share cookies you have to set cookie domain to .yourdomain.com, otherwise it will default to blog.yourdomain.com, so it won’t be shared:

SESSION_COOKIE_DOMAIN = '.seenreport.com' if not DEBUG else '.localhost'

And that’s it! Enjoy Django!

Posted 3 years ago

CommonJS Module System in Ruby

I really like the CommonJS module system, which is explicit, rather than implicit as Kernel#require in Ruby. So rather than putting everything into the global namespace, require in CommonJS simply returns an object which contains the stuff you explicitly exported from the required file. For example:

var sys = require("sys");
sys.puts("Hello there!");

And in the sys.js can be something like:

exports.puts = function (foo) {
  process.stdout.puts(foo);
};

Surprisingly, it’s really easy to implement the same in Ruby using method_missing and singleton_method_added. The first hook method is used for registering properties via exports.a_variable = a_value, where method a_variable= obviously doesn’t exist and the second hook for registering methods:

def exports.foo; end

This is the best syntax for defining methods on modules, but then a_module.foo obviously won’t trigger method_missing because it actually exists. But we want to register it into a container with all the properties and methods, so we can iterate over it etc. Fortunately the solution is really simple:

def exports.singleton_method_added(method)
  @data[method] = self.method(method)
end

This will be called each time a method will be added into the exports metaclass. So then when we’ll call import, we’ll get something like:

require "import"

sys = import("example")
# => #<CommonJS::Proxy @data={:language => "Ruby", :VERSION_ => "0.0.1", :say_hello=>#<Method: #<CommonJS::Proxy>.say_hello>}>

Nice, is it? You can check the code at my GitHub account, I named it commonjs_require. It’s definitely worthy to take a look even if you aren’t interested in CommonJS, because it’s a really good example of Ruby flexibility.

Anyway it could be interesting to implement some more Node.js stuff in Ruby, mainly because it’s asynchronous and therefore waaay better. Consider for example this:

fs = import("fs")
fs.watch_file("/etc/hosts") do
  puts "Hosts file changed!"
end

I’d definitely utilize this kind of stuff. Since this kind of stuff is already implemented in EventMachine, it could be +/- just a simple DSL around it. Is anyone interested?

Posted 3 years ago

Why You Don’t Need OOP in JavaScript (So Much)

After I did some research on OOP in JavaScript, I realized I don’t need it so much. I’m used to do pretty much everything via OOP, since it’s the way how Ruby, my primary language works. But JavaScript is different.

Both these languages have require function. But there is a fundamental difference how these functions work:

# ruby
require "logger"
# => true

// javascript
var sys = require("sys");
// => { print: [Function]
//       , puts: [Function]
//     , debug: [Function]
//      , error: [Function]
//   , inspect: [Function]
//          , p: [Function]
//        , log: [Function]
//      , exec: [Function]
//  , inherits: [Function]
// }

See? In Ruby require simply puts everything into one global namespace, whereas in JavaScript require() returns an object. So you don’t need to have a class for encapsulation.

The second big difference is that in JavaScript functions are actually closures. In Ruby there are closures (blocks & procs & lambdas), but functions aren’t closures.

// requires
var model = require("model");

// setup
var db = new model.riakClient(8098, "localhost", {debug: true});

// functions
exports.get = function get (key, successCallback, errorCallback) {
  model.get(db, "projects", key, successCallback, errorCallback);
};

In Ruby you would usually create a class and have a class variable @@db, but here you can just define a local variable for the context in where you define your functions. So you don’t need to have a class for sharing some data

In JavaScript I tend to use composition as a replacement for inheritance. For example on my current project, I have some models. I’m not using any ORM, just a library for talking with database of my choice. I have a model.js with common functions and then I have a file with functions for each model. Each this file simply wraps functions from model and that’s it. In JavaScript it’s much easier than to deal with inheritance, especially because I’d need to deal with inheritance of class methods etc and it would be just too big and heavy.

Posted 3 years ago

My Node.js Projects

  • Minitest.js is a simple testing framework designed for testing asynchronous code. It’s light-weight and it’s not trying to reinvent the wheel, so it doesn’t have any assertion helpers, because it expects that you simply use standard assert library.
  • Task.node is a very simple task manager (imagine Make/Rake/Scons, but it doesn’t suck as Make or Rake :) ). It’s also very simple and light-weight.
  • Colours.js is a small module for providing colours to your CLI programs. It doesn’t define any functions, it just name colours, because it’s much easier to do colours.bold.green + "Hello there!" + colours.reset than "\x1B[1;32m" + "Hello there!" + "x1B[0m"

Minitest.js in action (it’s using colours.js):

Minitest.js in action