понедельник, октября 02, 2006

IF/UNLESS блоки в RJS шаблонах

Недавние занятия программированием с Ajax в Rails привели к созданию патча для поддержки создания IF блоков в javascript'е. Основная идея (помимо условий в виде строк) - поддержка элемент-прокси:

page.if page['element_id'].visible do
page['element_id'].hide
end

Проблема в том, что page['element_id'].visible сгенерит код до того, как будет обернуто в IF блок.
Также можно использовать более традиционные методы:

page.unless "$('element_id').visible()" do
page['element_id'].show
end

Патч был отклонен в core, но было предложено сделать плангин для обкатки.

Собственно, вот и он: http://rubyforge.org/projects/js-if-blocks. Инсталировать можно так:

./script/plugin install svn://rubyforge.org/var/svn/js-if-blocks/trunk/js-if-blocks

Тепрь думаю о добавлении возможности повторного использования proxy объектов, например:

element = page['element_id]
page.if element.visible do
element.hide
end

7 комментариев:

Анонимный комментирует...

Maxim,

This is absolutely fantastic work. We've just hit the same issue, and were about to write similar code when some Googling turned up your plugin. Very many thanks!

Just one quick comment - the URL to install the plugin is wrong. It should be svn://rubyforge.org/var/svn/js-if-blocks/trunk/js-if-blocks

Unknown комментирует...

Wow, thanks for feedback.

I wrote this plugin to help myself in my work.

When I suggested a patch to Rails Icore, DHH declined it because he wanted it to get more tested.

So I published it as a plugin, but it seemed that no one ever needed such feature. No one got excited.

I'm glad that it helped someone besides me. Feel free to report bugs and I'll see what I can do with it.

PS I'm surprised that I get a response from non-russian speaking people too, though the post is written in russian.

Анонимный комментирует...

Well, although I can't read Russian, it was pretty clear from context, and your previous article here.

Maybe an English version of this page would help people get "excited"? :-)

Unknown комментирует...

Oh.. Just forgot about the previous post =)

About english page:
1. It is hard to maintain two versions of the page
2. The blogger doesn't allow to sort posts to different categories (although there is a concept of "labels") and have a separate feed for each category ("label").

About the excitement: I did some suggestions to people in RoR mailing list to use this plugin to people that had similar problems, but got no response.

The same thing with nested_layouts plugin which I released not so ago. I had seen only 1 mention in someone's else blog about it. How do you guys produce applications with no ability to nest layouts in one another ?

It seems that there is some black magic involved or I don't understand something.

Анонимный комментирует...

Такая же фигня, и знаешь, судя по форумам у многих. Так что полезная штука, глупо что такого нет изначально в RJS. Они несколько раз отклоняли подобные тикеты.

Анонимный комментирует...

Да уж блин, оно не инсталится. Ты уверен что путь правильный?

Unknown комментирует...

Только что проверил - все инсталится. Проблема в другом - весь путь не видно, ибо его закрывает часть лэйаута, а из-за того, что он находится в PRE блоке, он не переносится.
Даже и не знаю что лучше - или переносить (хотя, видимо, оно все равно не уместится, ибо длинное), или оставить так.
Делайте так: берем мышкой и выделяем не "слева направо" а "сверху вних" (тыкаем на начало строки и тащим мышь в начало следующей строки). Тогда весь скрытый текст будет выделен (только что именно так и проделал).

В конце должно быть /var/svn/js-if-blocks/trunk/js-if-blocks