Wednesday, December 22, 2010

RRTE Public Alpha

Hey people, sorry for being quiet recently, been busy with work and stuff. I don't have a pretty picture for you today, but Santa didn't come up giftless today, not at all :)

I've got a cute little link for you!

I just pushed RRTE alpha to github, so you could have a sneak pick on what's going on.

It's still an alpha, it doesn't work under IE yet and you might stumble upon some bugs here and there, but generally, generally it all shapes up and should give you some basic overview of the thing.

Anyhow, you know the drill. Checkout, enjoy and come back with feedback! :)

Wednesday, December 1, 2010

RRTE Status Update

Hey folks! It's been couple of weeks and some of you started to wonder, where's Nik with his RRTE and the world domination, so here is the status update.



As you can see, we are having some serious progress. Most of the things you see on the picture are already working, but I'm trying to explore some possibilities and features.


What's Wrong With the World?

It seems that the design-mode support in browsers is utterly broken. It's ugly, limited, uncomfortable to use and behaves differently in different browsers. Well, just like the whole JavaScript business :)

There is basically two modes how the design-mode works in browsers, the tags mode and the css-mode, in the first one the browser tries to use tags to style the content, in the other one it tries to use styles. The trouble is that IE supports the tags-mode only and FF supports both, but in any case both of them do that wrong.

You see, in the tag mode say they use obsolete FONT tag to style fonts, but in this case FF doesn't support for example proper selections highlighting, they also for example use STRIKE instead of S tag and there is no way specify it. In the css-mode, the browsers try to use things like style="font-weight:bold" instead of the <B> tag pair, which is quite inflexible if not to say idiotic in terms of CSS. It also incorrectly reacts on all sorts of things, like say it will show the U tool "on" when you put your cursor on a link, and you won't be able to switch it off because it's styled with css.

And so one and so one. There is are lots of small and big fuckups like that, and honestly it is quite a mess.


Time To Fix It!

Being an arrogant idiot, I couldn't just pass by this mess, so now I'm building my own engine, which will do precisely what we need on any browser. Basically there are two sets of tools, one of them allows you to work with the style attribute, the other one allows you to format anything with any tag you want, and, what's more important, with any attribute you need, which means that you can use ids and classes as well.

The formatting setting is not limited to the H1-H6, PRE and ADDRESS tags anymore. You can easily specify say things like that

Rte.Formats = {
'h2': "Header 2",
'tt': "Typetext",
'blockquote': "Block quote",
'div.blue': "Blue block",
'div.green': "Green block"
};

Etc, etc. The basic plan is to create some sort of a mixed, truly css-oriented mode. We will use SPAN + style attribute for things like custom colors and fonts, but for everything else use normal tags and classes, so that the editor produced a nice and easy to process and support content.

It's a bit tricky, but we will get through it.


Advanced Tools

The other thing which I'm trying to figure out is how small an RTE can be, or how much features can we squeeze in 10k? Advanced OOP features of RightJS are really helpful in this case, because all the inheritance and functionality injection features allow us to create really compact and flexible code. As you can see I already added the color tools, font name and size tools, formatting options and some other things. At the moment all of that weights about 8k of gzipped code (and that includes all the css).

So I'm trying to add more features in the standard package than I originally planed and see where it will lead us. We might drop some of them into the extensions pack later on, or, if everything will go smoothly, we might not need one and all the standard functionality will be available in the basic build, so that we will have just a core and plugins. Or something like that. Will see.


--
Well, this is basically it for the moment.
To be continued...

Friday, November 12, 2010

RightJS RTE Concept

In case you were wondering why it was quiet around here for last couple of weeks, I'd like to share some stuff I've been secretly working on and what are the future plans.

Basically we are taking a little pause until Mozilla guys sort their stuff out and release FF4 or at least 3.7, which we need to execute our evil plan for RightJS 2.2.

Meanwhile I've been working on this puppy



Yup, it's a RightJS based RTE that will most definitely take over the world, and so you started to want it for xmas, I'd like to put some words in about what's what and stuff.


Meet RRTE The Frameless

One of the major differences from usual RTEs is that our RTE (which goes under the codename RRTE) does not use any frakking frames. Instead, it uses an inlined DIV with contenteditable="true" property.

If now you're wondering what it gives you, then this is what:

Because it's an inlined div, all the content inside of it will follow all the styles on the page, which means no more headache with transferring and applying your styles to some iframe. If you take a look at the picture, you'll see that the header text inside of the editor has exactly the same font and size as the header on the main page. The blockquote and pre tags are also painted through usual CSS right on the page.

Secondly, because it's just a small inlined piece of page, RRTE works and feels much faster than any IFRAME based editors. It is super fast, practically it feels almost like a plain textarea element.

Thirdly, because all widgets in RightJS UI are plain elements, you will be allowed to easily access and manipulate any content right inside of the editor via standard API.


Modular

The second most important feature of RRTE is that it will be modular. Unlike all the other heavy duty RTEs, our RTE, by default will be mainly social networks oriented. It's main purpose will be to work as a lightweight embeddable RTE for all sorts of things like comments and blog posts where you already have all styles in place and just need some nice and shiny thing instead of textareas.

For this reason the default package will contain the main core/engine and provide basic editing tools which you can see on the picture above. Currently it weights just 4k of gzipped code (including stylesheets) and my intention is to keep it under 10k size.

And for all the advanced functionality, like file-pickers, fonts, tables, etc. we will have a separated package, which will turn the editor in a normal heavy duty RTE.


Extendable

As you can see, my plan for RRTE is to extend it via plugins. I don't have any intention to implement everything in it, instead of that RRTE will have a proper OOP design in best RightJS traditions, so that you could make your own tools and extensions, using classes and inheritance. In case if you're wondering how it's gonna look like, here is an example how the Save button is implemented


Rte.Tool.Save = new Class(Rte.Tool, {
shortcut: 'S',

initialize: function(rte) {
this.$super(rte);
if (!rte.textarea.form()) {
this.disable();
}
},

exec: function() {
if (!this.disabled) {
this.rte.textarea.form().submit();
}
}
});

RRTE will provide you with basic tools and open API, so I expect it to be pretty civilized and easy to extend.


What and When

Currently I keep all the fun for myself. This thing is not on github yet, basically because I hack and refactor it alot. Some parts are still quite flimsy and as I don't want you to have a wrong impression about it I'm going to keep it locally for the next week or two.

At the moment it appears to me that I'm done on about 40-50%, but as I'm a bit busy those days it is hard to estimate the exact schedule. Judging by my guts I should push something worth of seeing on github in about couple of weeks and probably will have the first release by the end of November/beginning of December.


This is basically it. Enjoy the news!

--
Oh, and one more thing. I could use some help with a default iconset for this widget. Currently I use some free stuff that I found over the internet, but if you can and willing to draw some particularly cool uber-iconset, that would be much appreciated!

Monday, October 25, 2010

RightJS 2.2 Notes

I'm cooking a new evil plan for RightJS 2.2 release and would like to share some thoughts and notes, so you knew what's going on and where are we heading.


Native Fx

We are living in an interesting moment. Native CSS transitions are finally becoming reality. Safari does it, Chrome does it, Opera does it, FF4 does it (they promised they will include the feature into the 3.7 release). IE9b does not. Rumors has it, the feature will be in the final release, but I have my doubts it will happen.

Anyways, now, when the majority of sane browsers support the feature, I think it's the right time to start using native CSS transitions as a default option for our dom-morph effects. It is faster, simpler and more reliable.


Better UJS

The current implementation of UJS in RightJS works with an event target property only. The trouble with this solution is that when you have something like

<div id="one">first
<div id="two">second
<div id="three">third</div>
</div>
</div>

and you attach an event listener to say the top one

"div#one".onClick(function() {
...
});

it will reacts only if the user clicks on the div#one itself and will successfully ignoring clicks on the inner element. Sometimes that's what you need, but in majority of the cases it creates more confusion than helping.

I'm still thinking about this one, but there is a good chance that the logic will be changed and our UJS will mimic the normal event listeners behavior and react on inner elements as well.

Hey! You will be able to make UJS stuff within UJS stuff! :)


Cookie plugin

At the beginning it seemed like a good idea to have a basic Cookie wrapper out of the box, but later I realized that on majority of my projects I don't use it. Well I assume you have pretty much the same experience.

So I think the cookie module will be kicked out of the core into an officially supported plugin. it's not much, just half a KB of gzipped code, but I guess we can fill this half a K with something more useful in everyday life.


IE8 And Pals

IE8, or as it known in some circles "IE7 on steroids" is kinda of troubling browser. The problem is that on a good half of the pages this darn things automatically falls into IE7 mode and therefore downloads the "olds" module, on the other half, it still has some troubles with native css selectors because some of CSS3 constructions are not supported, which consequentially makes some wonder-people to wonder how "right" right.js exactly is?

Furthermore the change/submit events still don't bubble and we carry quite large chunk of code in the core, to work this thing around.

So I was having that wild thought in my head, that we could ditch IE8 and pals support into the olds module so we could fix those things in there and not bother the core.

Currently, I'm considering the idea of making the line between the old and new browsers right where the CSS transitions support starts, which will effectively drop the whole IE support into the olds module.

That probably will make some jquery folks to moan that we are unfair towards them, but I'm looking into my glass ball and it says that after all the cutting and stitching, RightJS core size could drop below 12k.

Well, at least that the target. Besides there is still a tiny chance that IE9 folks will hear the voice of sanity and add css-transitions into it, then this distinction will be perfectly justified.


---

Anyhow, those are the notes and thoughts. Let me know if you have something on your mind about that

Thursday, October 14, 2010

Cloned SELECT elements in IE

What I love about IE browsers is that genuine feeling of moral superiority that you unavoidable accumulate inside yourself when you're dealing with its features. Found one more "treasure" that killed half of my day.

The story goes like that. Say I have a SELECT element and then you clone it a bunch of times and populate with new content, kinda like that

var original = document.createElement('select');
clone = original.cloneNode(false);
document.body.appendChild(clone);

$(clone).html('<option>boo hoo!</option>');

And that all works fine, but now say you update the content in another function, say an ajax callback or something

var original = document.createElement('select');
clone = original.cloneNode(false);
document.body.appendChild(clone);

setTimeout(function() {
$(clone).html('<option>boo hoo!</option>');
}, 0);

You would expect that this is no different from the first example and here is where they will get ya. Not only it does not update the options list (it will be empty), but it also somehow manages to show you that the innerHTML property was actually updated and contains all the new data.


// .....

setTimeout(function() {
$(clone).html('<option>boo hoo!</option>');
alert(clone.innerHTML); // -> '<option>boo hoo!</option>'
}, 0);

All versions affected 6,7 and 8 (didn't test in 9 though)

In case you really really need to update a cloned SELECT element in an async callback, here is a hack how you can do that


// ....
setTimeout(function() {
$(clone).html('<option>boo hoo!</option>');

var dummy = document.createElement('option');
dummy.text = 'dummy'; // DON'T use innerHTML in here!
clone.add(dummy);
clone.removeChild(dummy);
}, 0);

It will fix the problem, but you'll need to add some checks in there to ensure it's actually IE you're dealing with.

That's the whole gotcha. Hope will save someone's day

Saturday, October 2, 2010

Making Pretty CLI Applications In Ruby

Sometimes we need to process large amount of data in Ruby, convert things from one format to another, process a large database, etc. And when you start implementing those things as rake tasks or something like that you need some feedback, say to see the progress and so one. Normally people would use puts

index = 0
count = things.size
things.each do |thing|
do_something_about thing

puts "#{index +=1} of #{count}"
end

But when you have several thousands or millions things to process this approach doesn't work, because it will just blow into the console, which is ugly and well... there are ways to do it much better, prettier and more professionally looking.

There are gems and libs that will help you to do it properly, but in this article I'd like to show how it actually works internally.


Strings Rewriting

One of the first things you might want to learn in order to make seriously looking CLI app is how to rewrite strings all over. It is a bit tricky in Ruby so here how it looks like. First of all you need to learn the "\r" symbol, which is called "caret return" and well it returns the caret. A simple example will demonstrate. Say you have a line of code like that

puts "one\ranother"

when you run it, you will see in the console a string like "another" and what's happening is that ruby will print "one" then return the caret and print "another" over it, so that you see the last one only. But the trouble is that if you'll write something like that

puts "one"
puts "\ranother"

It won't work and you'll see two strings in the console "one" and "another", and because of that if you'll put into your loop something like that

puts "\r#{index += 1} of #{count}"

it won't work either and you will see the same ugly roll of strings. To make it working you have to use the a combination of the print and STDOUT.flush calls, kida like that

8.times do |i|
print "\r#{i}"
STDOUT.flush
sleep 0.1
end

In this case it will print a string and stay on it. STDOUT.flush dumps the current stdout into the console, and on the next iteration, it will normally go to the beginning of the string and write it over as you needed.

But it is still not everything. If you run a piece of code like this one

%w{looooong short}.each do |str|
print "\r#{str}"
STDOUT.flush
sleep 0.5
end

You will see that on the second iteration, the previous line won't be entirely overwritten and instead of "short" you will see "shortong", to make it work properly you need to write a long enough string that contains spaces at the end, for example

%w{looooong short}.each do |str|
print "\r#{str.ljust(80)}"
STDOUT.flush
sleep 0.5
end

String#ljust makes a string of the given length by filling the remaining places with spaces. This way you will always overwrite 80 symbols of the line in the console.

To wrap it up nicely you might create a simple function and your loop will look like that

def print_r(text, size=80)
print "\r#{text.ljust(size)}"
STDOUT.flush
end

index = 0
count = things.size
things.each do |thing|
do_something_about thing

print_r "#{index +=1} of #{count}"
end
puts "\n" # <- a final new line



Displaying the progress

With the trick above you will be able to show a constantly updating status line, but there are still some meat on this bone. Showing the user things like "345 of 87654" is not particularly user friendly, because it might be a bit annoying to calculate the actual progress in your head all the time. Would be nice to show the progress in percents as well. Happily it is very simple to do using placeholders

print_r(
"%d of %d (%d%%)" %
[index+=1, count, (index.to_f/count * 100)]
)

The other usual problem with status reports is that you might have particularly large set of things, say several millions of them and your script might process several thousands of them per second. In this case hitting your console several thousands times per second will seriously slow the process down, so you might need a way to skip some steps and print reports in some periods of time. You can do that the following way

index = 0
count = things.size
step = count / 1000 # 1/10th of a percent

things.each do |thing|
if (index += 1) % step == 0
print_r "....."
end
end

As you can see we defined the step variable and then skip all the non-round iterations. In this particular case it will make the script to update the report every 1/10th of a percent of the job done. Which is in most cases is not a big drawback and still provides the user with progress updates.

You also might think of ETA calculations, but you probably can figure it out on your own now, it's very simple.


Add Some Colors

And the last thing I'd like to show is how to make colors in the console, which might make your application look even cooler. Some developers already know how to do that, but some don't. So here it is.

Basically it is very simple and in some ways similar to HTML tags. You use things called escape sequences which are just some markers like tags, you have an opening one, and you have a closing one, like that

puts "\e[32mGREEN TEXT\e[0m"
puts "\e[31mRED TEXT\e[0m"
puts "\e[36mBLUE TEXT\e[0m"

As you can see, the closing sequence is always the same and the opening one differs only by a number, and this number is basically describes the properties of the following text. It might be a color, or a blinking effect, you can nest them just like normal HTML tags and so one. You can find full list of options on wikipedia

The only trouble with those things is that the format of escape sequences differs from a platform to platform. The example above is for OSX terminal. How to make those things working in DOS and Linux you can find that on the same wikipedia page.


This is about it. Now go and make the world prettier!

Thursday, September 23, 2010

Easy Way Out of The STI Hell

I like the idea of STI (single table inheritance), it is cheap, dodgy but it works and allows you to play with all sorts of sub-types in a civilized way. For example you can redefine things in subclasses, use strategies and so one.

But when you try STI with Rails, you immediately fall into the polymorphic routes hell. Because you have new types, Rails tries to find routes for them, and it doesn't want to use the base model as a fallback. And here, people start to do all kinds of things (I did), define controller level helpers, generators, modules and so one. But then, someone adds a new custom method or a new subtype and it all falls down like a house of cards.

Well, you know what they say, the exit from a hell lays at the very bottom of it. And in Rails it will be routes. Say I want to handle all sorts of User model subclasses, like User::Admin, User::Manager, User::Blocked.

Trololo::Application.routes.draw do
# here I collect all the User subtypes
user_types = Dir["#{Rails.root}/app/models/user/*.rb"].map do |name|
"user_" + File.basename(name).gsub('.rb', '').pluralize
end

# and then I put all of them one by one
(['users'] + user_types).each do |name|
resources name, :controller => 'users', :path => '/users' do
member do
get 'stats'
end

resources :comments # we can define nested resources too
end
end
end

I use the Rails 3 notation in this case, but I suppose you can figure how to make it work under Rails 2 as well.

It is still a bit dodgy, but it is better and more stable than defining those type-specific routes manually in controllers, you also can automatically handle all the nested routes as well.

That's it, hope that will help

Thursday, September 9, 2010

RightJS 2 jQuerysh Plugin

Hey folks. I had couple of minutes of free time and cooked a fancy plugin for RightJS 2.

It's called 'jQuerysh' and provides the jquery-like behavior for the $() function. You can copypast or build it from over here jquerysh on github

Basically it does three things with the $() function. You can navigate in jquery-style

$('#element-id').onClick('addClass', 'marked');

$('div.class').each('addClass', 'marked');

And you can call the onReady via it, same way as in jQuery

$(function() {
// will be executed when on ready
});

This is pretty much it, might be useful for people who need to work with both jQuery and RightJS.

And yes, it works with RightJS 2 only. Not like I want to make you switch to RJS2 (which I actually want), RJS1 is simply not built for that.

Cheers

RightJS 1 Chrome Issues

As much as I like to think about webkit as the world's savior, it constantly produces all sorts of weird stuff in Google Chrome, the last update of which had killed some important feature in RightJS 1 (do those folks even think before they make such changes? because I guess it won't be a problem of RightJS only)

In any case, the shorts and longs of the story is that they screwed the Element#hidden() method, which broke down several UI units, Autocompleter, Calendar, Lightbox, Selectable and Tooltips.

I've published a package for you over here RightJS 1 UI Fixes. It has patched builds of all those widgets, plus a fresh RightJS 1 build with backports from RightJS 2.

If this core-build will cause you troubles, you can patch your own by a simple line of code like that

Element.insert({
visible: function() {
return this.getStyle('display') !== 'none';
}
});

And don't use the Element#hidden() method in your code, use Element#visible() instead.

Also think about moving to RightJS2, it works with wrappers and therefore doesn't have such issues by design.

Friday, August 27, 2010

RightJS 2 Release Plan Updates

My dear fellas, this lovely Friday's evening I'd like to share with you some updates on the RightJS 2.0 release plan. And yes, by "updates" I mean delays.

No need for dirty swears, because there are two good reasons for that. 1) Rails 3 which should come out any moment now, and 2) upcoming IE 9 beta which is scheduled to September 15th. And as we all know well those funny MS folks, I think you'll agree that it's better to wait couple of weeks rather than pull your hair off later.

And it's not all that bad, there are good news too. I'm almost finished porting the UI modules to RJS 2, which means there well be the RC2 release in about couple of days I think. RC2 will include the core with all the latest updates and all the plugins and widgets ported to the new system. Generally this will be the final version and unless someone find a bug it will go to the actual release as is.

You'll have couple of weeks to play with it until the IE 9 release, and I'll have couple of weeks to brush up the docs, update rightjs.org and rework right-rails. Thinks that should give as a good runaway for a nice and smooth release.

This is about it. Take care!

Tuesday, August 17, 2010

RightJS UI 2 The Battle Plan

Hello people. As I'm currently elbow deep in porting rightjs-ui modules to RightJS 2, I'd like to share some ideas and thoughts behind the changes so you knew what to expect.


RightJS 2 With New UI System

First of all the RightJS 2 release will be not just the core release, there are lots of cool new features and some dramatic changes, so I'm porting all the plugins and ui widgets to the new development approach, and with the RightJS 2 release I'll release updates for all the plugins as well.

This way we will have some sort of a clean slate, and you'll be able to start with all new tools right away.


Widgets === Elements

One of the biggest change in RightJS 2 is those really cool object-oriented dom-wrappers feature, and in the RightJS UI 2 we will take full advantage of it. If in the current system all the widgets are classes with some limited interface, in RightJS UI 2, all the widgets will be inherited from the dom-wrappers, so you will be able to manipulate with them as if they were normal elements.

// say you have a calendar unit
var calendar = new Calendar({
// some options
});

// now you can do anything you want as if it was a normal Element
calendar.insertTo('my-element', 'top');
calendar.addClass('my-calendar');
calendar.set('id', 'my-calendar-id');
calendar.onChange(function() {
// do something about it
});

// you also will be able to access it through the standard navigation methods
$('my-calendar-id'); // -> the 'calendar'
$('my-element').first('div.my-calendar'); // -> the same calendar

// it will be also follow the general inheritance structure
calendar instanceof Calendar; // -> true
calendar instanceof Element; // -> true

You've got the picture, everything you can do with any element on the page you will be able to do with the widgets and do that directly.


Unified Initialization

RightJS UI were growing a bit chaotically during the last year and we have some diverse ways to initialize units. With the new release all of them will work via the same initialization process with the same principles. The rel hacks are gone, instead of that we will use the HTML5 data-widget-name attributes.

<input data-autocompleter="{url: '/some.url'}" />

<input data-calendar="{format: 'US', hideOnClick: true}" />


Meta-framework and Modularity

In current incarnation all the RightJS UI widgets are pretty much independent, which means that we have some duplications here and there, same things work slightly different, not really clean styles and so one.

It's time to refactor the mess, with RightJS UI 2 there will be a meta framework which will provide common bits of elements and styles, like say buttons, panels, spinners, various common functionality and so one. This way we will have a consistent elements behavior over the widgets, plus it will be easier to create new widgets with the common blocks of code already existing.


Unified Stylesheets

The stylesheets also will be cleaned up and unified. There will be common classes for buttons, panels, spinners and so one. One of the reasons is that now we will be able to create skins in a civilized way.

There will be no actual skins with the release, we simply do the preparation work, but the skins constructor is one of the first things to do right after the release.



Summary

As you can see with RightJS 2 release we will bring to the next level not just the core, but the ui modules as well.

I've already ported the Autocompleter and Calendar widgets, you can check it out at the 2.0.0 branch on github. I estimate it will take about a week to port the rest of them to RightJS 2.

After that there will be RC2 release where I'll publish RightJS core and all the modules for tests. And in about a week after that (by the end of August) we shall release.

This is about it.

And btw, if you have thoughts about new features for some of the existing rightjs-ui widgets, that's a really good moment to let me know.

Now that's it.
Take care!

Saturday, August 7, 2010

DOM-Wrappers In RightJS 2

Put your tin-foil hats on people, because it's your next brainwashing session about upcoming RightJS 2.

When you heard that RightJS 2 is going to have dom-wrappers instead of direct dom-units access you might think "oh, that's not a big deal, jQuery has dom-wrappers from the very beginning!". And you will be dead wrong! I already touched it a bit in one of my previous articles, now let me show this beauty in details.


DOM-Wrappers == Classes

First of all, dom-wrappers in RightJS are not just a bunch of functions behind a namespace, dom-wrappers in RightJS essentially are normal classes, with inheritance and functionality-injection support. For example you have the basic class Element and two subclasses Form and Input, which means you can say normally call instanceof on them.

$('div') instanceof Element;   // true
$('div') instanceof Input; // false
$('div') instanceof Form; // false

$('form') instanceof Element; // true
$('form') instanceof Input; // false
$('form') instanceof Form; // true

$('input') instanceof Element; // true
$('input') instanceof Input; // true
$('input') instanceof Form; // false

You also can extend them separately and all the methods will follow the inheritance structure principles

Element.include({
global_method: function() {
// this method will appear on all elements
}
});

Input.include({
inputs_only: function() {
// this method will appear on Input elements only
}
});

You can use polymorphism, redefine the meaning of methods, etc. For example the Element#select will search for matching elements by a css-rule, but Input#select will put the focus on the input element and select its content. No problem, you can do that easily.


Define Your Own Wrappers

The usual extending methods like Element#include, Form#include are fine, but in RightJS you are also allowed to define your own wrappers for certain types of elements. For example you can define a tables-sepecific wrapper

Element.Wrappers.TABLE = new Wrapper(Element, {
sortBy: function(column) {
// sort the table body
}
});

Or you could create a textareas wrapper the same way

Element.Wrappers.TEXTAREA = new Wrapper(Input, {
spellcheck: function() {
// spellcheck the content
}
});

NOTE: we inherited the Element and Input classes as you would normally do with any other classes in RigthJS.

Once you've done that, anytime you access a table or a textarea you'll have those new methods available

$('my-table').sortBy('name');

$('my-textarea').spellcheck();

This feature will let you to adjust and completely redefine the framework itself for the needs of your application.

But this is not the most kick-ass thing yet. Because we have much more!


Private DOM-Wrappers

With RightJS 2 you are not limited to the actual dom-nodes and tags. You can define your very own private dom-wrappers that won't be tied to the framework structure in any way. Why would you need that? The answer is simple - widgets.

How do you normally write a widget? You create some class which aggregates some main element and then you have all the headaches with different contexts and bindings, because half of your logic is in your class and half is in your elements

var MyWidget = new Class(Observer, {
initialize: function() {
this.element = $E('div')
.onClick(this.clicked.bind(this));
},

clicked: function() {
// do something about it.
}
});

Then more, you'll have to create several proxy methods to delegate the methods to actually insert the widget on the page and do other normal dom-manipulations and so one and so one. In more or less complicated case those things tend to get quite messy.

Well my friends, you don't have to suffer anymore, because now you can define your widget as a private wrapper and inherit any existing dom-wrapper directly just like that

var MyWidget = new Wrapper(Element, {
initialize: function(widget_id) {
this.$super('div', {
'id': widget_id,
'class': 'my-widget'
});
this.onClick('doSomething');

// build your entire widget over here
},

doSomething: function() {
// do something about the click
}
});

NOTE: now you never leave the actual element context, don't need to worry about bindings, and then, can manipulate with your widget as a usual element on your page.

var widget = new MyWidget('widget-id');
widget.insertTo('some-element', 'after');
widget.addClass('custom-class');

// more of that!
$('widget-id') instanceof MyWidget; // true!

And there is more! You can inherit your private wrappers as any other and create different versions of your widget!

var MySuperWidget = new Wrapper(MyWidget, {
initialize: function(widget_id) {
this.$super(widget_id);

this.onClick('doSuperThing');
},

doSuperThing: function() {
// do the super thing over here!
}
});

You can create abstract widgets, share modules between them, do any sorts of crazy things, the possibilities are endless! And at the end, you still have an Element, which you can toss around the page in the usual way.

---

Oh yes my dear fellas, RightJS 2 will help you to kick some serious ass! The right way!

And this is about it. Come over for the next session, it will be fun!

Thursday, August 5, 2010

Prepare Your Project For RightJS 2

Some notes for those lucky of you who already is hooked to RightJS and the ones who think about giving it a try, but afraid that when RightJS 2 will start saving the world, the ones code will go south.

Rule #1 don't panic, despite of all the massive changes in the dom-stack and all the new finest kickassery, the actual API almost didn't change, just instead of real dom-nodes/events/etc you will receive some proxy objects, which have the same exact API. The difference is that you will have no direct access to the dom-unit attributes, so if you want your code to be working both in RightJS 1 and RightJS 2, use the Element#get, #set and #has methods instead.

// instead of this
$(element).id = 'boo-hoo';
var id = $(element).id ? $(element).id : 'default';

// write it like that
$(element).set('id', 'boo-hoo');
var id = $(element).has('id') ? $(element).get('id') : 'default';

If you need to access an element innerHTML use a simple patch like that

Element.include({
html: function() {
return this.innerHTML;
}
});

Later, when you will migrate to the actual RightJS 2, just remove it, RightJS 2 will have this method out of box.


Rule #2 don't access `window` and `document` directly, when you need to access some of the RightJS methods, put them through the same `$()` function first as you do with the dom elements

// instead of those
document.onReady(function() { ... });
window.sizes();

// call it like this
$(document).onReady(function() { ... });
$(window).sizes();


Rule #3 don't use `Form.Element` this unit will be renamed to Input in RightJS 2, so don't touch it or create a simple reference like that

var Input = Form.Element;

and work with the Input object instead.


This is about it. If you follow those three simple rules, all your code should be in working condition when you switch to RightJS 2.

Sunday, August 1, 2010

The Circus of Web Development

You might think of the web-development area (or sphere if you will) as some sort of a circus. For example.

Say there is an elephants show of Java developers, they big, slow, but precise. Then there is a exotic pet show of Python developers. Fearless camel riders with the perl guys. JavaScript people will be magicians, weird fellas who make things appear and disappear by some flimsy tricks.

Then there are a bunch of trained monkeys of Ruby kids (yes my agile friends we are :)). ASP.NET folks will be gipsy fortune-tellers, barely connected with the reality and no-one listen to them. And there are bears on monocycles in silly turkish hats, those are the PHP people (you are comrades, you are).

Clowns! Those will be the web-architects. Just like the real clowns, they barely can do a thing properly, and yet, they think they own the circus.

Saturday, July 31, 2010

RightJS 2.0.0-rc Is Out

Okay folks, RightJS 2 came to the point where it has a proper number and the '-rc' suffix in it's name. And here are some notes on the new sweet features we have since the beta release.

You can download the build over here, the archive contains both normal and safe-mode builds.

Generally this is almost the final line, I've finished packing it with new features and this is practically all we will have in the actual 2.0.0 release. There might be some tweaks here and there during the plugins and UI modules porting, but nothing dramatic. So lets check what we've got.


Dom Wrappers

In RightJS 2.0 we have a new kick-ass object oriented dom-wrappers system. Our dom-wrappers are essentially classes, with types, inheritance and all the nice functionality injection features. Currently we have the following wrappers Window, Document, Event, Element, Form and Input, which formerly was known as the Form.Element unit.

Dom-wrappers work transparently and have all the same nice API we had in RightJS 1, the only difference is that instead of the actual dom-element all the methods now operate with dom-wrappers.

$('element-id')  // -> dom wrapper
$$('#css .rule') // -> a list of dom-wrappers

All the dom wrappers are inherited from the same unit called `Wrapper` and have a common property called `_` which refers to the raw dom element, for example

$('element-id')   // -> Element wrapper
$('element-id')._ // -> the actual dom-node

$(window) // -> Window wrapper
$(window)._ // -> the window object

$(document) // -> Document wrapper
$(document)._ // -> the document object

So every time when you fill like it, you can always quickly access to the raw unit the same way across all the wrappers.


Dom-Wrappers Typecasting

As you might noticed we have three types of wrappers for dom-elements, the Form and Input classes are subclasses of the Element class and when you access your dom-elements they dynamically typecasted

var element = $('my-form');
element instanceof Element; // -> true
element instanceof Form; // -> true
element instanceof Input; // -> false

var element = $('my-input');
element instanceof Element; // -> true
element instanceof Input; // -> true
element instanceof Form; // -> false

This way you can check which type of element do you have and you can extend all of them separately


Element.include({
global_method: function() {}
});

Form.include({
forms_only_method: function() {}
});

Input.include({
inputs_only_method: function() {}
});

You even can use polymorphism and use the same method names

And you also can define your own types, for example

Element.Wrappers.TABLE = new Wrapper(Element, {
orderBy: function() {}
});

Later on there will be also private dom-wrappers which you can use in your app without extending the RightJS core and interfere with other applications.


Bubbling Dom-Events

RightJS also received several fixes for the traditionally problematic dom-events like focus, blur, change and submit, now all of them properly bubble on all the supported browsers.

There is nothing kinky about it I didn't use any special event names, just use the usual ones like nothing happened.

$(element).on({
focus: ...,
blur: ...,
change: ...,
submit: ...
});

I also added the custom events bubbling. If in RightJS the custom events didn't go anywhere from the node where you fired it, now they properly bubble up to the document object, so you can take advantage of them using the events-delegation technique.

Speaking of which.


New Events Delegation API

In the later releases of RightJS 1.5 we already had some elements of the events-delegation feature support, now it's time to take it to the next level.

First of all the String unit now has all the same API as Element, so you don't need to learn nothing new, just use what you already know.

"#div .span".on('click', function() {...});
"#div .span".onClick(function() {});
"#div .span".onClick('addClass', 'marked');

// you also can make the normal checks
"#div .span".observes('click'); -> true
"#div .span".observes('mouseover'); -> false

// and you can unbind the listeners the usual way
"#div .span".stopObserving('click', function() {});

Then the Event.delegate and Event.behave methods are gone and instead of them we have a proper events delegation API on dom-wrappers which look like that

$(document).delegate('click', '#css.rule', function() {});
$(document).delegate('click', {
'#css.rule1': function() {},
'#css.rule2': function() {}
....
});

// delegation checks
$(document).delegates('click');
$(document).delegates('click', '#css.rule');

// disabling delegation
$(document).undelegate('click');
$(document).undelegate('click', '#css.rule');

More of that the same API was adde to the Element wrapper so you can attach your delegating listeners at any level of your web-page

$('my-list').delegate('click', {
'li.one-thing': function() {}
'li.another': function() {}
});

This way you can scope the delegation to some block of your document and handle the things locally.

You also can delegate custom events too

$(document).delegate('bingo', {
'#one': function() {}
'#another': function() {}
});

$('one').fire('bingo');
$('another').fire('bingo');

Generally there are no limitations and you handle any sort of events simultaneously via the same api.


$$ Is Back!

As you might noticed I moved the $$ function back. I tried to use the jQuery-like unified $ method but didn't like it and brought the $$ back.

Amen.


Semi-Safe Mode

As you might know RightJS 2.0 will have the safe-mode build, which will hide everything behind a single RightJS object and won't extend a thing on the user's page.

A typical use case would look like that

RightJS.$('element-id').onClick(....);

var MyClass = new RightJS.Class({
...
});

There is also a way to access the language unit extensions by passing variables through the RightJS object

RightJS(['boo', 'hoo', 'doh']).filter('includes', 'oo');
RightJS(4).times(function() { .... });
RightJS('boo hoo').endsWith('hoo');

In the RC release I added a semi-safe API for the non-safe builds, meaning you can put your variables through and access the RightJS units via the RightJS object. This way if you need say to write a plugin that supposed to be working in both safe and non-safe modes, you can simply write it for the safe-mode and it will be working in the non-safe mode too.


JSONP Support

In RightJS 2.0 there is the JSONP format support for the Xhr unit. It all works transparently via the same Xhr API with all the same principles, the only thing is that now you have the jsonp option where you can specify your callback name variable, or simply use true for the default 'callback' value.

new Xhr('/some/url', {
jsonp: 'myCallback',
onSuccess: function() {
// ....
}
}).send();

Xhr.load('/some/url', {jsonp: true});

It even will assign the responseJSON and json varaibles

Xhr.load('/some/url', {
jsonp: true,
onSuccess: function() {
console.log(this.json);
}
});



New Language Level Methods

There are also several new javascript level extensions were added. Object.each, Array#reject (which is useful with calls by name), Array#min, Array#max, Array#sum

Probably something else that I have forgotten.



The Next Steps

Now when the core is finished, there are quite a lot of work with porting the plugins to the new version and reworking the documentation. The site also needs to be reworked to support the new building system.

At the moment I estimate it like 2-3 weeks of work. So the delivery-day is somewhere by the end of summer.

Okay, think that's all I have for know.
Take care!

Friday, July 30, 2010

Why Albeit Packing Is A Bad Idea

Okay I did it quite a lot on RightJS, but I've learned my lesson. A quick and self-explanatory example would be like that.

Say you have the following piece of javascript

a1.looooongMethod();
a2.looooongMethod();
a3.looooongMethod();
a4.looooongMethod();
a5.looooongMethod();

Being an optimization junky, you might think, "Oh! I can make it smaller!"

var b = 'looooongMethod';
a1[b]();
a2[b]();
a3[b]();
a4[b]();
a5[b]();

Then you look at the size, the first one weights 104 bytes and the second one 70.

"Woohoo!", you say, "30% optimization!". And will be wrong.

Because when a web-server gzips your code, the first one will weight 61 bytes and your optimized version will be... TADA! 72 bytes. Yup, bigger than it was before 8)

That's the whole story. Gonna go and unoptimize things back now.

Monday, July 19, 2010

Freezing Terminal.app in OS X

I ran in a strange bug yesterday on my macbook. Suddenly the Terminal.app started to freeze when you lunch it or open another window.

I killed half a day trying to figure out what's wrong with my HDD, and trying to restore parts of the system from a backup, but then found out that the problem was in another place.

So if you run into the same issue the cure is simple.
sudo rm -rf /private/var/log/asl/*

Apparently there is some problem with the log files that cause circular read/write calls, so when you nuke the old logs, it will get just fine

Tuesday, June 29, 2010

The RightJS DOM-Wrappers Speed

Okay folks, there is your next brainwashing session to keep you hooked to the right stuff.

When I announced that RightJS is switching to dom-wrappers, some of you seems started to panic. "Oh, no!", you said, "RightJS is going down, because native extensions murk dom-wrappers any day at any time!"

Well people, you just haven't seen the right wrappers yet 8). Here is the shot of the new engine in its raw, not fully optimized state.


FF 3.6.6


And so you didn't think that it's just FF, here is a shot in Opera.


Opera 10.54


Don't have a short for IE though, because didn't quite make it there yet, but you can imagine that it will go sky rocket, because there will be no elements extending anymore.

Some of you, young and sharp, might notice that, the ID access went down for a notch. That's all because of you guys, that's because in RightJS 2, you'll have the same $ method behavior as you have in your beloved jQuery, meaning you'll navigate it like that.
$('#boo-hoo'); // -> an element by id
$('div.boo, div.hoo'); // -> elements by the css-rule

There also will be things like $(window) and $(document), so you'll feel yourself like home.

That's about it. Hold on to the next session!

Saturday, June 26, 2010

RightJS Development Status

Hey folks, to keep in touch, some notes on the RightJS development status.

As you probably already know the next step in the RightJS evolution is coming. Currently I do all the fixes and main feature updates in the 'master' branch and all the dramatic changes go into the 'two.o.o' branch. So if you'd like to see what's going on, go and check it out from github.

So what's actually going on?

New building system

First of all I move the source code building system from the amaturish concatenation of some pieces of code to more serious layouts based builds.

What does it mean?

It's fairly simple. Instead of having all sorts of small isolated pieces of code, now we have one global function which isolates the RightJS initialization process inside. It doesn't mean that RightJS now closes its insides like jQuery does. No, all the crazy monkey patching abilities remain in place and it is still an open architecture, but now we don't need to worry about accidentally polluting the global scope with some temporary variables, plus it gives us a great deal of optimization abilities in speed and size.

Secondly, now we use the google's closure compiler to compact the javascript code. It works a bit faster and provides slightly better results than my FrontCompiler.

I haven't finished yet with all the size optimizations yet, but the layout based builds + google-compiler are already giving us some benefits. Despite that I already added quite a few new features and methods, the size of the builds went down at about 1K and goes like 40K of the minified (not packed) code, which is about 15K in gzip.

Then it seems like I'm going to get rid of the albeit-packed builds. The reason is that most of the web-servers those days use gzip compression and in this case there is no significant difference between the packed and minified versions. And as the packed version initializes slower than the minified one I think there is not much of reasons to continue to support it.

In any case, you'll be able to albeit-pack RightJS with FrontCompiler at any moment by yourself.


The Safe Mode

The are another reason for the layouts based builds - the safe-mode development. And currently there are several directions which the safe-mode development goes.

First of all the name spaced mode. Now as RigthJS initializes inside of a layout, it extends the global scope only at the very end. So you can easily have a name spaced build by removing one line of code from the end of the file and all the RightJS global objects will be available in the scope of the RightJS object.

You still will have all the native and dom object extensions with all the benefits and troubles and your code would look like that

with (RightJS) {
var MyClass = new Class({
include: Options,

initialize: function(id) {
this.element = $(id);
}
}
}

Or, if you're against the with calls, like that

var MyClass = new RightJS.Class({
include: RightJS.Options,

initialize: function(id) {
this.element = RightJS.$(id);
}
}


The second direction is so called condom-mode. The idea is that we initialize RightJS in a separated IFrame and then hook up the main window to the functionality via the RightJS object. In this case you have almost complete isolation of the contexts, RightJS won't touch the main window units and you also will have access to the RightJS fancy native extensions like that.

var R = RightJS;

R('boo.hoo').endsWith('hoo');
R(4).times(...);
R(function() { }).bind(...);
R([1,2,3,4]).without(2,3);
R.$('element-id').onClick(....);

RightJS will extend only those dom-elements which you actually work with. So you'll still have the RightJS speed and easy goingness, but you also have the ability to safely implement say widgets on someones page.

The condom mode is mostly ready, it still has some unfinished parts with the window and document access, but all the other things are already working. you can build and play with it in the `two.o.o` branch like so

rake build OPTIONS=safe



The DOM-Wrappers

The condom-mode is just a step to the next level, it is an interesting thing but it still does extend dom-elements you access. So I'm currently working on the next step which is the dom-wrappers.

The idea is to replace the direct dom-elements access with some artificial proxy which will have all the same interface as a normal dom-element but without actually extending the dom-elements themselves. The reasons are obvious, it's a peaceful coexistence with another scripts on the page and better cross-frame scripting abilities/performance.

This feature is still in progress and you'll see the first results in about couple of weeks.

After that, that's it, we release.


The Summary

One way or another, with the 2.0.0 release we should fix the only problem that wrong with the right javascript framework, the safety. We will have normal quick and naughty builds as we have now, but we also will have options with the namespaced and condom modes.

Which means we will have a rock-solid safety against the anxious MSIE or any other browser that will think its smarter than others, and you also will have the ability to use RightJS to develop widgets in the safe-mode.


That's about it.
Have fun!

Wednesday, June 2, 2010

Postion fixed in IE6

If you old enough you might remember that wonder of technology we used to admire something like ten years ago, which also known those days as the zombi-browser aka IE6. And if you old enough and unlucky enough to have a need to make something with "position:fixed" under that browser, you might think about the usual approach with hooking up the window.scroll event with some piece of javascript and move the thing manually.

My dear friend, there is a better way to hack the shit out of it. Presenting you the CSS hack which will keep your element fixed at the bottom of the window
div.sweet-div {
position: fixed;
bottom: 0;

/* IE6 position:fixed hack */
_position: absolute;
_bottom: none;
_top:expression(eval(document.compatMode && document.compatMode=='CSS1Compat') ? documentElement.scrollTop +(documentElement.clientHeight-this.clientHeight) : document.body.scrollTop+(document.body.clientHeight-this.clientHeight));
}


Enjoy!

Friday, May 21, 2010

Making a Colorpicker

The other day I've been implementing this colorpicker widget for RightJS and now I'd like to share some mathematics and mechanics behind the widget.

I won't bore you to death describing the actual layout, just some necessary theory and math. And I also will use RightJS semantics. Well, just because I love it.

The Color Theory

Lets start with a bit of a theory. Every giggling school girl those days knows that any color can be created by a proper mix of three basic colors, red, green and blue. That's a brilliant idea, but the problem is that not many people actually can use it. Personally me, I don't know anyone who can instantly say how much of every color you need to take to create say a color of coffee and milk.

And because of this problem the humanity created another, more natural way of color picking which is based on another three dimensions: tone, saturation and brightness. And the main idea of the colorpicker widget is to convert one system into another.

The Tone Parameter

The tone picker usually looks like a vertical bar and represents the following system of colors.



The principle is that with this tone scale you can have any tints available with full saturation and brightness. Note also that in every point of the scale, one of the colors is always has a zero value, and at least one of them has the full value.

Keep also in mind that this scale is some sort of closed circle, the end on the right is actually joined with the beginning on the left.

The Saturation And Brightness

The saturation and brightness field usually looks like that.



The saturation parameter is zero at the left side and have the full value on the right. The brightness is full at the top and zero at the bottom. This way, you will always have the white color at the top left corner, your current tint color at the top-right corner and a black line at the bottom side.

With those three handlers you also can chose any visible color but in more natural way.

Converting TSB into RGB

The first task of the colorpicker is to convert the tint, saturation and brightness parameters which the user picks into the actual RGB value.

It was proven that the best way of keeping your values in this case is if you keep your TSB parameters in float values of range 0..1 and RGB values in integers of range 0..255. This way you won't have systematic round up errors and it will be working faster.

So your TSB -> RGB script will look like that
var tint = [1, 0.5, 0];
var saturation = 0.6;
var brightness = 0.4;

var color = [0, 0, 0];

for (var i=0; i < 3; i++) {
color[i] = 1 + saturation * (tint[i] - 1);
color[i] = (color[i] * brightness * 255).round();
}
The principle is simple, first we combine the tint and saturation which will give as a raw color in range 0..1, then we apply the brightness parameter and convert the float value into a 0..255 integer.

Converting RGB into STB

The backward conversion is a bit trickier. I've drown a simple picture to help you understand the principle



Say you have some RGB color with values in range of 0..255. Remember our tint picture, where one value is always 1 and another is always 0. So this smaller area between the green and red values is the same thing, if you take it and normalize to the 0..1 range you'll have your clear tint values. The brightness parameter will be the proportion between the brightest color and the 255 value, and your saturation is relation between the minimal color to the maximum.

The script looks like that
// the initial RGB value
var color = [200, 100, 50];

// finding the minimal and maximal values
var color_sorted = color.clone().sort(function(a,b) { return a-b; });
var max = color_sorted[2];
var min = color_sorted[0];

// calculating the brightness and saturation
var brightness = max / 255;
var saturation = 1 - min / (max || 1);

// calculating the tint
var tint = [0, 0, 0];
for (var i=0; i < 3; i++) {
tint[i] = ((!min && !max) || min == max) ? i == 0 ? 1 : 0 :
(color[i] - min) / (max - min);
}
It is pretty much straight forward, but we also have some failsafe conditions like (max || 1) and (!min && !max) in case if all the RGB values are zeros.


HEX to RGB Conversions

And couple more things which you also will need. Converting your 0..255 colors array into HEX and RGB formatted strings back and forth.

Converting an array to a HEX value is simple
'#'+ color.map(function(c) {
return (c < 16 ? '0' : '') + c.toString(16);
}).join('');

Converting RGB string into an array of values looks like that
if (match = /rgb\((\d+),(\d+),(\d+)\)/.exec(value)) {
return [match[1], match[2], match[3]].map('toInt');
}

And converting any HEX color into an array can be done like that
// converting the shortified hex in to the full-length version
if (match = /^#([\da-f])([\da-f])([\da-f])$/.exec(value))
value = '#'+match[1]+match[1]+match[2]+match[2]+match[3]+match[3];

if (match = /#([\da-f]{2})([\da-f]{2})([\da-f]{2})/.exec(value)) {
return [match[1], match[2], match[3]].map('toInt', 16);
}

Well, that all you need to know to make one cool colorpicker of yours.
Enjoy!

Tuesday, May 18, 2010

Automatic Records Search in Rails

There is one neat trick I'd like to share. In many cases, especially when you work on intranet applications, you need say to check some security settings against the data-records before you let the request to access the actual method in your controller. Normally, most folks do that by adding before filters to find the records, like that

before_filter :find_this
before_filter :find_that

def find_this
def find_that

When your application grows and starts having something like a dozen models, plus you might have nested routes where you need to check the security against the nested elements too, those things tend to get really messy.

So here is a simple method which I use on my projects

before_filter :find_restful_units
def find_restful_units
params.each do |key, value|
if key == 'id' || key.ends_with?('_id')
unit_name = key == 'id' ? controller_name.singularize : key.gsub('_id', '')
unit_class = Object.const_get(unit_name.camelize)
instance_variable_set("@#{unit_name}", unit_class.find(params[key]))
end
end

rescue NameError # just hung up if there is no such unit
nil
end

You put this in your ApplicationController and it will automatically find and assign all your models, the actual and the nested ones.

This makes controllers much cleaner and you always have your models extracted and ready to use in the standard way.

Wednesday, April 28, 2010

RightJS vs. MooTools In The Game of Mines

This weekend I had some fun implementing the good old game of mines using RightJS. The result is pretty cute, you should check it out. No, really, you will like it.

The thing is that about year and a half ago I implemented the same exact game using MooTools, you can check it out over here, and well, I have some words to say on this regard.

Okay, I certainly did get better during this last year and you might say that I know RightJS better than MooTools, but here are some numbers. (For the sake of a clean experiment I specifically didn't look into the old code before or during the development and eventually gone in a different approach in the implementation.)

With MooTools I was working on the game almost the whole week, I didn't work full time and as I recall it you could say it were good three, three and a half days of work. The result is 14k build of JavaScript + about 5k of CSS, which is about 19k in total.

In case of RightJS it took me about 6 hours to implement the whole thing from top to bottom, and the result built of JavaScript + CSS is just 9K of code.

Yup, a twice as compact result and about four times less time spent. More of that I believe that RightJS implementation has much cleaner and easy to understand code.

The really sweet things in case of RightJS were the number extensions, simplified collections processing and built in Observer unit. It feels so good and natural to implement game logic with them! I really enjoyed those things!

Well, that's about it.

Monday, March 29, 2010

RightJS + Rails = Love

As the right-rails (the Ruby On Rails plugin for RightJS) was updated recently, lets have another brainwashing session. This time for Rails people.

If you're a kind of a pragmatic developer, you're probably asking yourself "why would I fall in love with this new thing? I already know Prototype and jQuery why would I need something else?", and believe me, I know precisely what you mean.

But ask yourself, being a Rails developer, were you ever happy of doing AJAX features in Rails? No, I mean, not like first two weeks on rails, or things like "it's working". I mean really happy, did you feel funny about Prototype or jQuery? Did they make the butterflies in your stomach fly? Literally.

Think about it. The Prototype support on Rails was always a kind of a flimsy hack and most serious developers don't really use those RJS stuff. And with jQuery you were always left alone to deal with all those kinky JavaScript stuff. That's good if you are a JavaScript guru and know your magic. But what if you are not, and what about the actual Rails business anyway? Did any of the frameworks really helped you in any way to be an actual Ruby/Rails developer?


How Is RightJS Different?

First and most important thing you should know about RightJS is that it was written by a Ruby/Rails developer for Ruby/Rails developers. And despite the fact that from time to time we have all those arrogant promotions and we mock jQuery folks constantly. RightJS is not really about JavaScript itself. It is something quite opposite.

RightJS is all about getting JavaScript off your hair. RightJS is made to help Ruby developers to deal with JavaScript tasks, it reflects Ruby way of handling things, has mostly Ruby syntax and many of its key features are copies of Rails features.

RightJS civilizes JavaScript and brings it closer to Ruby developers.

But we didn't came here to talk about JavaScript, right? What about Rails itself?


Lets Make The Butter Fly

How much time does it take to make a date-time field with a calendar in your framework?

Let me spare you the calculations time and show how it looks like in RightJS + RightRails.

<% form_for(@zing) do |f| %>

<%= f.calendar_field :dead_line %>

<% end %>

Nope. I didn't forget nothing. `calendar_field` is all what it takes. RightRails automatically includes all necessary JavaScript, CSS and I18n modules on your page and initializes the fields, so you don't need to worry about a thing.

More of that, it will automatically swap between builds and source code for JavaScript in production and development modes.

So, would you like some rater or slider on your form?

<%= f.rater_field :rating %>
<%= f.slider_field :completeness %>

Oh, I know! You'd like some autocompleter, right?

<%= f.autocomplete_field :category, :url => categories_path %>

Would you like the autocompleter to be RESTful design and hard-caching friendly? No problem!

<%= f.autocomplete_field :category, :url => "/categories/%{search}.js" %>

Here you go.


And That's Not All

The fun is not over, not by a long shot. The next feature is that RightRails comes with a brand new RJS generator, and that's not just a collection of dummy functions like in the case of the Rails original RJS templates.

The new generator lets you literally write JavaScript in Ruby and more of that it allows you to mix Ruby and JavaScript calls in one flow escaping and transforming variables on fly.

For example this is how the annoying nested forms look like when you make them with RightRails.

<% form_for(@zing) do |f| >

<div id="categories">
<%= render @zing.categories %>
</div>

<%= link_to_function 'add' {|page|
page[:categories].insert(render(Category.new))
} %>

<% end %>

See, the `insert` method is a JavaScript function, the `render` is the ActiveView method, `Category` is your model. All in one flow with automatic types conversion. And it is not just a list of predefined functions, you can literally do whatever you want.

update_page do |page|
page[:todos].update render(@todos)

page[:todos_count].innerHTML = @todos.size + ' Items'

page[:todos].select('li').each do |item|
item.onClick('toggleClass', 'marked')
end

page.json_variable = @todos.to_json
page.items_count = @todos.size
page.list_updated = true

page.alert "There are #{@todos.size} items left on the list"
end

There are no limiatations.

Mommy Look, More Fancy Stuff!

Oh yes mommy, there are! On top of all RightRails has a conventional interface to cover the most common AJAX CRUD operations. Let me show you.

Say here's your remote form

<% remote_form_for(@zing) do |f| %>

<%= f.text_field :name %>
<%= f.file_field :picture %>

<%= f.submit 'Create' %>
<%= image_tag 'spinner.gif', :class => :spinner %>

<% end %>

And here is your controller method

dev create
@zing = Zing.new(params[:zing])
if @zing.save
render rjs.insert(@zing)
else
render rjs.replace_form_for(@zing)
end
end

The `rjs` method provides access to the new RJS generator from the controllers, and `insert` and `replace_form_for` are the AJAX operations interface.

It all works over the Rails conventions, the `insert` method looks for the class of the `@zing` model, finds related partial, renders it and generates a piece of JavaScript that inserts the HTML into an element with the `zings` ID.

The `replace_form_for` method will render a new form with all the error messages for the @zing model and generate JavaScript that will update the form on the page.

RightRails has a collection of such methods for all CRUD operations.

Note also that I've put a file field and a spinner image on the form. RightRails automatically and transparently processes files uploading too, basically there is no difference whether your form has files or not, it all has the same API. And the RightJS when submits a form via AJAX, automatically searches for images with the `spinner` class and uses them as spinners, you don't need to hook them up with callbacks manually.

Summary

I'm not going to indulge you with obvious conclusions, I'll just tell you that I've already used RightJS + RightRails on two production projects and it saved me hell of a lot of time and nerves on JavaScript and AJAX development.

Well, it was designed to.

Saturday, March 27, 2010

Supervisor Mode With Authlogic

Supervisor mode is a feature that allows site admins to quickly switch to any other user (say customers) and take a look at the site the same way the customers see it, may be perform some actions from this user, etc.

So here is a simple tip how you do that using the Authlogic plugin for Rails.

First of all you'll need couple new routes, one to switch to some user, another to get back to the admin mode.

map.super_login '/login/:id', :controller => 'user_sessions', :action => 'super'
map.back_login '/login/back', :controller => 'user_sessions', :action => 'back'

I used two new methods named 'super' and 'back', which are not exactly RESTful, but you can use 'edit' and 'update' if feel particularly evil about it. They are normally not used in the 'user_sessions' controller.

After that on the list of customers you add links to switch under this user, for example like that

....
%td= link_to 'Supervision', super_login(user)
....

And finally you'll need those two methods in your `UserSessions` controller

class UserSessions
.....
# switches under this user
def super
raise AccessDenied if !admin?
session[:original_admin_id] = @current_user_session.user.id
@current_user_session = UserSession.create(User.find(params[:id]))
redirect_to '/'
end

# switches back to the admin -mode
def back
raise AccessDenied unless @current_user_session && session[:original_admin_id]
@current_user_session = UserSession.create(User.find(session[:original_admin_id])
session[:original_admin_id] = nil
redirect_to '/'
end
.....
end

The idea is simple, in the first method you stash the original user_id in a session variable, then create new user session with that specific user. And in the second one we restore the original user in the session.

You also might consider to add two methods like `current_user` and `current_user=` in your application controller they are pretty useful and will make your code cleaner.

class ApplicationController
...
# returns the currently logged in user
def current_user
@current_user_session.user if @current_user_session
end

# assigns the currently logged in user
def current_user=(user)
@current_user_session = UserSession.create(user)
end
...
end


That's all. Have fun!

Friday, March 5, 2010

Mechanize and MultiSelect fields

Mechanize is a little handy tool that allows you to perform all sorts of HTTP requests in Ruby. It automatically emulates all sorts of browsers, handles cookies, headers and stuff, which is really useful when you need to harvest some data from sites that don't have any computer friendly feeds.

I'm using it on my current project and run into a small problem. It doesn't work nicely with array data, like for example multiselect fields emulation, so when you do something like that

agent = Mechanize.new

agent.post('http://boo.boo/boo', {
'param[]' => ['one', 'two', 'three']
});

In the reality it sends the 'one' value only. I've sent a little patch to the devs, but it seems like it will take time before they do something about it. So here is how you fix it in your rails app.

In any initializers in your `config/initializers/` directory add the following lines.

class Mechanize::Form::Field
def query_value
if @value.is_a?(Array)
@value.collect{ |v| [@name, v || '']}
else
[[@name, @value || '']]
end
end
end

After that it will be just fine.

Tuesday, March 2, 2010

My Top 5 on that RightJS vs. jQuery Question

During the last several months of RightJS promotion, the absolute hit among the questions of 'what?' and 'why?' was understandable the question of what is the difference between RightJS and jQuery.

There were lots of talks about RightJS speed and then more about speed, and then we had some abstract talks about its philosophy and its way among the others and we also have that simple comparison page.

And what I find important in a brainwashing process is systematicness and methodicalness. We did some talks on an abstract matter, we did some talks on the opposite side of scale with performance tests, now lets touch something real. Something in the middle. And probably summarize some previous talks.

So here it is, your next session; my top 5 as I see it at this morning.


1. Syntax

When I'm saying "jQuery is like PHP", first of all I mean the nature of its syntax. When you boil it down to the essence, both of them are just collections of helper functions. And as PHP defines a new kinda language upon C, almost the same way jQuery defines a new language upon JavaScript.

RightJS on the other hand is built right into JavaScript itself. In 90% it is the good old JavaScript, where we bring features from later JavaScript specifications and spice it with some standard features from more serious dynamic languages like Ruby and Python.

As the result, when you learn jQuery, you mostly learn jQuery, I've seen many nice fellas around, who know jQuery quite well, but stuck when they needed to do simplest things in pure JavaScript.

When you learn RightJS, you learn the actual JavaScript, yes we have some funny shortcuts and features that make mature web-developers happily giggling like school girls, but all of them are built upon JavaScript standards.

RightJS makes you do the things in JavaScript and do them right. And because of that, whatever the future brings, your knowledge and skills will remain with you.


2. The Actual STL

When I read someone saying "jQuery is the JavaScript STL", it usually makes me laughing so much, that my neighbors probably think that I've finally went nuts and going to blow off the Kremlin.

Now, don't get me wrong, I have no problems with jQuery's popularity and I respect that. Well, at least, as long as it keeps me away from people who doesn't know the difference between popularity and standards.

jQuery is a DOM DSL at best. First of all it doesn't have anything to do with JavaScript itself, because it's a DOM wrapper, secondly there is nothing standard about jQuery in terms of JavaScript. Take for example a look at the .each() function where the arguments are in just the opposite order than they are in the JavaScript own Array#forEach method.

If you need something that actually follows the standards, you should take a look at RightJS. It brings many standard features from later JavaScript specifications, plus many other none the less standard features from server-side programming languages, for example methods like String#startsWith or Array#random.

The DOM interfaces are just one part of RightJS and it has much more. We even have a build of RightJS without DOM features which you can use on the server-side with Node.js or say writing scripts in Qt.


3. Multiple Paradigms

As jQuery is simply a wrapper over DOM interface, it doesn't give you any alternatives but use its own way of dealing with the things. Yes, you might imagine that you're practicing Lisp in JavaScript, but the reality is that 99% of jQuery code (including jQuery itself) is just a spaghettish pieces of crap.

RightJS on the other hand is not just a DOM wrapper, it is a multi-paradigm framework. We have an advanced OOP stack that allows you to write clean and properly designed applications that are easy to support and refactor. We also have most of the standard FP features, like binding, curring, chains and stuff. We also have some standard native units extensions that are most helpful in procedural programming.

RightJS gives you options and flexibility, so that you could deal with your work in the most effective way.


4. Open Sandbox

Maybe jQuery forces you to write a spaghetti code, but there is a bigger problem. Most of jQuery and its plugins code are closed behind anonymous scopes that makes it impossible to change them part by part.

You know, people are actually already invented OOP, inheritance, functionality injection and other fancy stuff to deal with those sort of things. And that's why in RightJS we have radically opposite architecture.

RightJS is built using proper OOP structures and modules and it represents an open sandbox where virtually everything is accessible and customizable. You can easily bend and tune RightJS for your needs, changing and replacing its parts, adding your own features, methods and so one.

And because of that it is super easy to write any sort of plugins and extensions for RightJS. Take for example a look at the right-rails plugin; couple of dozens of lines of code and RightJS API was completely transformed to have the naming system of Ruby, with underscored syntax and other features.

RightJS gives you the same flexibility and hacker's joy as Ruby or Python.


5. Official Plugins

I'm sure you know what they say "jQuery has a gazillion of plugins that will do everything for you". It kinda reminds me other folks who was saying "Everything in Java has already been done".

Normal people usually add on that "badly".

That gazillion of plugins has actually a pretty nasty back side. The problem is in the closed architecture and inflexibility. For every case there are usually half a dozen of implementations, and quite often the choice is like "bad, bad or bad?". At the end you might spend more time looking for a proper plugin than you could spend writing it yourself, and at the finish your app will look like a Frankenstein, all stitched of different parts.

Yes I know, I know, Frankenstein is a romantic figure in gothic culture, but there is so few romantic in supporting such an app.

With RightJS we don't have the luxury of too many plugins, but we have several good points on that matter too. First of all, many common and frequently used features that you have as plugins for jQuery, are already baked into the RightJS core, like for example, additional form features, Ajax via iframes functionality, cookies and stuff.

Then we have all the standard plugins, like D'n'D, JSON, Behaviors, plus most of the standard UI elements like Calendar, Autocompleter, Tabs, Lightbox, etc. already implemented and served in the official plugins repository.

And what's different about RightJS plugins is that all of them are implemented in the same way, using the same set of rules. All events handling, options, usage principles all are the same. So that if you had experience with one plugin, you will be familiar with the rest of them too.

Then all the plugins follow the open-sandbox principles of the RightJS Core. All of them are implemented using proper OOP approach and can be easily extended using inheritance, functionality injection or even monkey patching if you will.

This way you don't need a dozen of variations of the same plugin, you can easily tweak any standard one to do exactly what you need.

Friday, February 26, 2010

Native Element#classList in FF 3.6 Against RightJS

As many of you probably aware, FF 3.6 has the HTML5 Element#classList feature implemented natively. And then @DouweM asked if we could add it to RightJS.

Well, I tried, but the thing is that those guys at Mozilla could do it better. They have the test, the picture and yet another 2x times performance improvement, awright.

But lets check it out by ourselves, shall we?

I've created this little script which has two implementations, one uses FF 3.6 native feature, another one uses the same pure JavaScript algorithm we use at RightJS to handle css-classes. And here's a screenshot of my test-run.



Seems like RightJS implementation murks a native feature again. It's more than three times faster on classes adding :)

So how did those guys at Mozilla get their results?

They simply used lousy RegExp based implementation of the feature in their test. Surely it was slower.

This is pretty much it. Hope they will fix it in the next releases of FF.

Saturday, February 20, 2010

Recent jQuery Performance Updates

Now folks, you know, I was always saying "there is nothing like a smell of good statistics in the morning!". Now lets take a look at that 2x speed up claimed over here.

I'm using my Shakker util to perform the tests. You can also read why I don't use Taskspeed anymore.

So to the tests. Lets take a look at the Firefox test



Yea, kind a bit of speed up at claimed `bind`, `html` and `remove` methods, certainly not 2x, and note how it actually got slower at 1.4.1 and then gets back to almost the same values as 1.4.0.

Now lets take a look at the same thing at Safari



A different scale, the same picture, it's getting slower from 1.4.0 to 1.4.1 and then gets back to almost the same values at 1.4.2. No 2x speed up between 1.4.2 and 1.4.1, more of that almost no speed up at all and certainly no 3x speed up agains 1.3.2.

Well, lets get further and take a look at the test in another fine browser, Chrome.



The same exact picture with the `bind`, `html` and `remove` methods, got slower on 1.4.1 and to the same value at 1.4.2.

Now you should get back to that release notes page and ask yourself "why there are no results for version 1.4.0?".

Yup, because there is no speed up, they merely fixed their own fuckups in 1.4.1 and now present it as 2x speed boost.
Awesome! :)

Slowing Things Down Under OS X

You know what they say "you need to slow down to see some certain things". In case of web-development, sometimes you need to emulate a realistically slow internet connection to see some problems with your project. See how quickly it loads up, how it receives the images, especially it useful to test file-uploads and ajax operations. So here is a little tip how can slow down requests to your local server to test the things properly.

Under OS X you have access to the FreeBSD traffic shaping util ipfw. First of all you need to define some rule which will work on local interactions.
sudo ipfw add 1 pipe 1 src-ip 127.0.0.1
sudo ipfw add 1 pipe 2 dst-ip 127.0.0.1

After that we can set up the connection speed, and also I like to add some delay to emulate a request to a remote server
sudo ipfw pipe 1 config bw 40Byte/s delay 100ms

After that all your local requests will slow down to 40Byte/s speed with a realistic 100ms response delay.

When you have done with your tests, you can remove the rule with the following command.
sudo ipfw delete 1

Now it is all interesting but lets wrap it up in a simple shell script so we didn't need to memorize all the fancy calls.
sudo touch /usr/bin/slowdown
sudo chmod +x /usr/bin/slowdown

After that open the file with your favorite editor and write the following little script

#!/bin/bash

if [ $1 = "clear" ] ; then

ipfw delete 1

else

ipfw add 1 pipe 1 src-ip 127.0.0.1
ipfw add 1 pipe 2 dst-ip 127.0.0.1
ipfw pipe 1 config bw $1KByte/s delay 100ms

fi

Now you can create and remove pipes just like that
sudo slowdown 40

And to remove the rule call it like that
sudo slowdown clear

That's all about it. Happy testing!

Sunday, January 31, 2010

Algorithm Complexity Analysis On An Interview

I was digging around trying to find what kind of questions Google interviewers ask potential candidates and found some guy story who was asked the following question:

"What is the complexity of searching for existence of all characters from one string into another?"

That guy answered "n*n", and after being rejected was wondering if it was "n*lg(n)". Poor little thing...

IMHO: Rule #1 when you're having an interview (I guess, especially at Google): "never trust the interviewer", it is their job and trade to mislead you and check how you actually think, rather if you know the correct answer.

So, here is how I would answer to that question. (yeah, I'm showing off, but please consider that as me simply exercising)

Okay. First of all the complexity vastly depends on an implementation. I can see at least three of them.

1. A blunt force solution, you just go through every character from the pattern string (p) and check if each of them exist in the text string (t). Strings are essentially arrays and search of any character in them have linear complexity. So that if we have n = |p| and m = |t|, then the overall complexity of the algorithm will be
O(n * m)

2. There might be another solution. If we pre sort the t string with say quicksort algorithm, then we can use the binary search, which has logarithmic complexity and faster than a blunt cell-by-cell search. In this case, considering that the quick-sort complexity is super-linear, the overall complexity will look about like that:
O(m * lg(m) + n * lg(m))

3. One more version. Considering that both strings consist of the same limited number of symbols, we can create two hash-tables, one will contain unique characters from the p string and another one will have characters from string t. As the alphabet is a limited list, finding of the intersection of those two tables will have a constant complexity. Plus we should add the complexity of building the hash-tables, which will be equal to the lengths of the strings. And the overall complexity will be
O(n + m + C) = O(n + m)

Roughly speaking, we can take a look at the case when n = m, then we can say the following about those three algorithms:

1. O(n*n) - quadratic complexity
2. O(n*lg(n)) - super-linear complexity
3. O(n) - linear complexity

I suppose the last one is the winnar.

--

This is about it.

I still do have that feeling that I'm gonna get my ass kicked in the upcoming interview, but at least I won't give up that easily and will throw couple of punches back.

Monday, January 25, 2010

How to Move Folders Between Git Repositories

Today I needed to move some folders from one git repository to another preserving the history. Evidently it's a tricky business, so here is how do that.

First of all you need to have a clean clone of the source repository so we didn't screw the things up.
git clone git://server.com/my-repo1.git

After that you need to do some preparations on the source repository, nuking all the entries except the folder you need to move. Use the following command
git filter-branch --subdirectory-filter your_dir -- -- all

This will nuke all the other entries and their history, creating a clean git repository that contains only data and history from the directory you need. If you need to move several folders, you have to collect them in a single directory using the git mv command.

You also might need to move all your content into some directory so it didn't conflict with the new repository when you merge it. Use commands like that
mkdir new_directory/

git mv my_stuff new_directory/

Once you've done commit your changes, but don't push!
git commit -m "Collected the data I need to move"

This is all about the source repository preparations.

Now go to your destination repository
cd ../my-repo2/

And here is the trick. You need to connect your source repository as a remote using a local reference.
git remote add repo1 ../my-repo1/

After that simply fetch the remote source, create a branch and merge it with the destination repository in usual way
git fetch repo1
git branch repo1 remotes/repo1/master

git merge repo1

This is pretty much it, all your code and history were moved from one repository to another. All you need is to clean up a bit and push the changes to the server
git remote rm repo1
git branch -d repo1

git push origin master

That's all. After that you can nuke the temporary source repository.