Hibernate - No CurrentSessionContext configured

20. November 2009

If you encounter an error like:

org.hibernate.HibernateException: No CurrentSessionContext configured!

you probably want to add this line to your hibernate.cfg.xml

<property name="hibernate.current_session_context_class">thread</property>

Ruby en Rails 2009 Conference in Amsterdam

3. November 2009

This year’s Ruby en Rails conference in Amsterdam was a great success. A lot of great speakers came together with an amazing audience.

Besides the two Rails talks from Jeremy Kemper and  Yehuda Katz there were a lot of really interesting talks.

Jonathan Weiss’ Talk about Rails Security, for instance, was very interesting and should be a must read for all rails people.

The lightning talks about DataMapper and MongoDB were also very good and I am totally looking forward to play around with these technologies.

I was wondering whether a off-topic like my talk about genetic algorithms in Ruby will be popular but surprisingly I received much positive feedback. Thank all you guys!

The code of my talk solving the traveling salesmen problem with genetic algorithms can be found on avarteq’s github account.

Slides are on slideshare.net:

Finally, many thanks to Chris and Tim Obdam who organized this outstanding conference. Hope to see you next year again!

RTeX::Document::GenerationError with Phusion Passenger

17. September 2009

In a recent project I experienced a RTeX::Document::GenerationError only when using Phusion Passenger. After a closer look I’ve seen that the PDF has been successfully created but the redirect to the following request failed. Everything works fine with mongrel.

However, the error messaged looked like the following:

RTeX::Document::GenerationError in BillsController#index</h3> <pre>Could not find result PDF document.pdf after generation.

[…]

In this case the Rails app renders a bill and sends it via email to the customer and then redirects back to the bill listing. The error does not occur during the bill generation. The email including the pdf will be send successfully.

The error happens in the redirection to bills_path. The latex log document.log show that Rails or RTex has rendered html as it should but then passed it to RTex to render a pdf from html (instead of tex).

Workaround

In order to prevent this behaviour I studied the gem and found the following workaround. After generating the PDF simply put

Thread.current[:_rendering_rtex] = false

before the redirect. The RTeX::Document::GenerationError should be gone.

Free Ruby - Email2sms - E-Mail to SMS Gateway

29. August 2009

Avarteq GmbH

Email2sms has been developed by www.avarteq.de.

Email2sms is a free and pure Ruby E-Mail to sms gateway including an extensible filterchain to filter and manipulate incoming emails before sending them as text messages.

Requirements

In order to run Email2sms you will need the following.

Required gems

  • developergarden_sdk
  • tmail

Installation

If it is the first time you install a gem from github you might need to perform the following command:

gem sources -a http://gems.github.com

Also have a lookt at gems.github.com for a brief introduction on how to install gems hosted by GitHub.

In order to install the actual email2sms gem invoke the following command:

gem install avarteq-email2sms

Configuration

The first time you start email2smd it will create the following directory:

ENV["HOME"]/.email2sms

Which basically means that it will create the hidden directory email2sms in your home directory (~/).

In addition to this it will create a configuration file template:

~/.email2sms/email2sms.yml

Now it’s you turn:

Open the config file and adapt it to your needs.

Usage

The basic usage of email2sms is straight forward. It’s mainly about starting and stopping the daemon.
Type

email2smsd -h

to get more information. This help is generated by the daemon gem so this message is not application specific but it will give you to get a short introduction about how to control the daemon.

Start

email2smd start

Stop

email2smsd stop

Watch output in

email2sms_main.rb.output

and

 email2sms_main.rb.log

for detailed application state information and errors.

The files are located in the folder you have configured in your configuration file.
By default this is the directory from where you have started the daemon.

Send e-mail

Ok, now you are ready:

In order to send an sms just send an email to the email adress configured in the email2sms.yml file.
If you use the subject filter then you will need to have the password in your subject line:

Subject:
mypass +49177 12344567
Message body:
Whatever

That’s it. Have fun!

Download @ GitHub

Ruby - Socket programming - TCPSocket - Documentation

24. August 2009

If you need to write an application using TCP sockets under Ruby you should have a look at the following docs:

Ruby Core RDoc:

http://ruby-doc.org/core/classes/TCPSocket.html

Programming Ruby, The Pragmatic Programmer’s Guide, Network and Web Libraries

MacOS X - Rails - RTex - Latex Installieren - Unicode - ucs.sty

15. August 2009

In order to create PDFs with unicode (utf8) support within a Ruby on Rails app on Mac OS X, you need a fully working Latex installation including the ucs.sty extension.

The best way to install Latex on a Mac OS X is using MacPorts. The following command will install Tex, Latex and a whole bunch of extensions:

sudo port install texlive texlive_texmf-full

You should be aware that the ports texlive and tetex don’t like each other.  It might happen that you need to remove all Tex or Latex related ports before installing the environment using the command mentioned above.

Without a working unicode extension you might encouter errors like:

! LaTeX Error: File `ucs.sty' not found.

after following the RTex-Error linkin to a file in

tmp/rtex/rtex-.../document.log

Ruby - Visibility of private and protected module methods when mixed into a class

7. August 2009

Consider you have a module defining a public, a protected and a private method. What happens to this visibility declaration after mixing the module into a class?
Does Ruby ignore visibility information or does Ruby take over the visiblity settings?

The following example demonstrates that Ruby preserves the module’s visibility settings and keeps private methods private and protected methods protected:

Output looks like this:

Public

Unable to call a protected method.

Unable to call a private method.

Protected

Private

Protected

Private

What we see is pretty much the same as declaring the module methods directly in our class. The fact that we use a mix-in didn’t change anything at all.

  • Our protected method may be invoked in MyClass as well as in MyInheritedClass but not outside of our classes.
  • The private method can only be used within MyClass but outside or in the inherited class MyInheritedClass.

So everything is just as expected. Isn’t Ruby a great thing?

Ruby (on Rails) - Wirble - Pimp my IRB and Console

20. July 2009

Ever wanted a colored irb or script/console? Well, you should try wirble. It gives you a number of enhancements for Irb.

Some of the features are:

  • Tab completion
  • Colorized results

Installation is easy as pie:
 sudo gem install wirble


vi .irbrc
require ‘rubygems’
require ‘wirble’

# start wirble (with color)
Wirble.init
Wirble.colorize

Ruby Basics - * method arguments

19. July 2009

If you have ever asked yourself what is behind arguments like *this then here is the trivial answer:

A small ruby script like this:

#!/usr/bin/env ruby

def my_method(a,b,*c)
puts “a: ” + a
puts “b: ” + b
puts “c:”
c.each { |ce| puts ce }
end

my_method(”a1″, “b2″, “c3″, “c4″, “c5″, “c6″)

Produces the following output:

a: a1
b: b2
c:
c3
c4
c5
c6

As you can see all arguments after a and b are collected in an array and passed to c.

Isn’t this nice?

Ruby on Rails 2.3 - Nested Attributes with AJAX support

12. July 2009

Introduced in Rails 2.3 nested attributes help to shorten code if you want to
edit multiple nested models within a single form.

Here the corresponding article from the rails weblog:

http://weblog.rubyonrails.org/2009/1/26/nested-model-forms

There is also a very good tutorial on nested forms from Ryan Daigle:

http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes

Right now it seems as if there is no clean way to have ajax enabled nested forms.

Let’s have a look at it in more detail using a simple invoice example.

Rails Nested Attributes Invoice Example - UML class diagramm

Each Invoice has one or more InvoiceLineItems.

Actually this 1:n situation occurs in nearly every Rails application but there are two things turning this into a special case. First, we will use the nested attributes feature which has been added in Rails 2.3. Seccond, we want to have an ajax enabled form where invoice items can be created, edited and deleted without reloading the whole page.

As mentioned before a very good guide on how to create a nested form without ajax capabilities is can be found under

http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes

This guide will be the foundation for this application so you might want to read it before reading further this article.

Note:
This is not meant to be a best practice suggestion. This article’s main intention is to show and discuss some of the problems you run into when creating ajax forms using nested attributes.

I tried to create a clean solution but I think things should be easier than this. So either I am somehow unable to see what I am missing or there is still some work to be done within the Rails framework itself.

Take the challenge!

If you see an easier way to overcome problems mentioned here feel free to drop me an email or post a comment.

Prerequisites

Before we start let’s create a non ajax enabled application as described in Rayan’s guide.
You can also find this non-ajax version of this app at github (initial checkin):

http://github.com/enterprise-rails/invoice_nested_attributes_ajax/tree/f7f676ad344cf1e364fcb7af86478332d1c18146

No we have our basic application which is able to create and update invoices including invoice positions (non-ajax). The application has still a limition. You can only create a single InvoiceLineItem since there is no way to tell the controller to add another one.

You could enhance the form by rendering it again passing an argument to add another empty InvoiceLineItem. But this is not what we want. We want to add an empty form to create another InvoiceLineItem by performing an ajax call. So what’s the deal about this?

If you have a closer look at new.html.erb form you will notice that the fields_for helper is invoked on the local variable supplied by form_for(@invoice). This is necessary because Rails internally checks the Invoice model while performing fields_for to determine whether invoice_line_items is declared as a nested attribute.

Rails generates special html ids and form names when detecting nested attributes such as:

<input id=”invoice_invoice_line_items_attributes_1_amount” type=”text” value=”100″ size=”30″ name=”invoice[invoice_line_items_attributes][1][amount]”/>

As you can see the name of the input element ends with _attributes and in addition to that is numbered ( …][1][… ).

More than that if you are editing an invoice and having a look at the html source you will see an additional hidden field added by rails helpers:

<input id=”invoice_invoice_line_items_attributes_1_id” type=”hidden” value=”2″ name=”invoice[invoice_line_items_attributes][1][id]”/>

Now that we know how the form should look like we can have a look at problems when trying to generate it within an ajax call.

Problem when creating the AJAX Call

The main problem when creating the ajax call is the missing form_for-context for our Invoice object.

At this point my expectation was the following. It should somehow be possible to use the field_for helper without creating a form context. We don’t want a form so why should I generate one? Ok, we need to provide the invoice object to the fields_for helper. This is necessary so that the helper can create all those nice html ids and form item names. But in an ajax call to enhance the existing form I definitely don’t need another form tag.

However, I am not an expert for rails internals so I had a look at the helper implementation to get a better understanding of the rails helpers. I found the implementation in:

lib/action_view/helpers/form_helper.rb

As you might know there are two ways to invoke a form helper; by calling a helper method such as fields_for withouth or by calling form.fields_for with a form context.

The implementation in form_helper.rb reflects this by having one implemention within the ActionView::Helper module and one in the ActionView::Helper::FormBuilder class.

Only the form builder implementation seems to be aware of generating nested attributes form elements.

I think this might be the main reason for the laking ajax support.

If you invoke fields_for like this

<% fields_for :invoice_line_items, @invoice.invoice_line_items.first do |ili_form| %>
<%= render :partial => ‘invoice_line_item’, :locals => {:ili_form => ili_form} %>
<% end %>

then you’ll receive a form but it’s not meant to be used within a nested form:

<input id=”invoice_line_items_amount” type=”text” size=”30″ name=”invoice_line_items[amount]”/>

As you can see form elements do not end with _attributes.

Workaround to get a form_for context

As an ugly workaround you could do something like this:

<% ActionView::Helpers::FormBuilder.new(:invoice, @invoice, @template, {}, proc {} ).fields_for :invoice_line_items, {:child_index => @next_child_index} do |ili_form| %>
<%= render :partial => ‘invoice_line_item’, :locals => {:ili_form => ili_form} %>
<% end %>

The trick here is to create a FormBuilder object and passing the Invoice object to it but throwing away all output from the form builder. We just use it to create the ili_form object which is another form builder instance. But this form builder has the needed context to generate correct elements for our nested form.

So how did we create the silent invoice form builder? Normally we would use the form_for method to create it. In this case we used the constructor method new. Since output within the form builder block would mess up our response we pass an empty proc instead of a block.

Again, I don’t like this very much and I would be glad if someone knew a better way to do this.

With this workaround we are able to add empty forms to add new invoice line items per ajax call. But since we have created an empty record on a new Invoice object the generated html ID and form names are not indexed properly. Index is always 0.

A closer look at the form_helper.rb source code shows that there is an option for fields_for called child_index.

Using this option we can generate an empty record with a certain index. But wait, how can we determine the correct index? The client could have added dozens of empty records on the client side.

I think the best way would be to have a look at existing records and determine the next index on the client side. If my last record has index 0 (can be taken from html ids or form names) the next index is 0+1 = 1.

We implement two javascript methods like this:

function max_html_seq_id(object_name, collection_name, attribute_name, field_to_count) {
if ( field_to_count === undefined ) {
field_to_count = ‘input[type=text]’
}
search_string = field_to_count + ‘[id^=’ + object_name + ‘_’ + collection_name + ‘_attributes]’;

   bp_fields = $$(search_string);
max_seq_id = -1;

  // ==> <input id=”invoice_invoice_line_items_attributes_0_amount” type=”hidden” value=”1″ name=”invoice[invoice_line_items_attributes][0][id]”>
bp_fields.each(function(bp_field) {

   // ==> “invoice_invoice_line_items_attributes_0_amount”
html_id = bp_field.id;

   // ==> ‘^invoice_invoice_line_items_attributes_(\d+)_amount’
reg_exp_str = ‘^’ + object_name + ‘_’ + collection_name + ‘_attributes_(\\d+)_’ + attribute_name;

   // ==> /^invoice_invoice_line_items_attributes_(\d+)_amount/
reg_exp = new RegExp(reg_exp_str);

   // ==> [”invoice_invoice_line_items_attributes_0_amount”, “0″]
match_ret = reg_exp.exec(html_id);

   // ==> “0″
seq_id_str = match_ret[1];

   // ==> 0
seq_id = parseInt(seq_id_str);

   // Maximumsuche
if (seq_id > max_seq_id) {
max_seq_id = seq_id;
}
});

   return max_seq_id;
}

function next_html_seq_id(object_name, collection_name, attribute_name) {
return (max_html_seq_id(object_name, collection_name, attribute_name) + 1);
}

Basically we perform a maximum search on indexes taken from text fields.

So we need to generate a button performing an ajax call which submits the calculated index as a parameter. This could look like this:

In your javascript file:

function params_to_new_invoice_line_item() {
return ‘next_child_index=’ + next_html_seq_id(’invoice’, ‘invoice_line_items’, ‘amount’);
}

In your view:

<%= button_to_remote “New line item”,
:url  => {:action => ‘ajax_new_line_item’},
:with => ‘params_to_new_invoice_line_item()’ %>

Since there is no need to modify the controller this should be enough to create and edit new line items.

Summary

The main question is whether there is a more elegant way to create a new invoice line item field set with a correct index prepared for the use in a nested form.

Maybe a modified FormBuilder or FormHelper?

Download the example

You can find the final app on github:

http://github.com/enterprise-rails/invoice_nested_attributes_ajax/tree/master

Git clone url:

git://github.com/enterprise-rails/invoice_nested_attributes_ajax.git