View Full Version : Can you expand an array of N to fill N functional arguments?

ralph l mayo
02-15-2007, 08:43 PM
I've made this abstract class other classes can implement to make themselves storable in a MPTT database scheme without having knowledge of the left/right juggling. In the new entry part of class, I need to be able to insert an arbitrary length hash (@attrs) into the database (using DBI). I can generate the SQL for N values, but when it comes to executing it the SQL DBI's execute() method will not expand an array to fill the arguments it is expecting.

I tried this first:

cursor = @dbd.prepare(
"INSERT INTO #{ @table } (#{ @columns['left'] }, #{ @columns['right'] }, #{ @attrs.keys.join(', ') })
VALUES (?, ?#{ ', ?' * @attrs.length })")

cursor.execute(l, l + 1, @attrs.values)

But execute() fails for @attrs.length > 1

This works, but it's very hackish:

exec_attrs = @attrs.keys.collect { |k| "@attrs['#{ k }']" }
eval "cursor.execute(l, l + 1, #{ exec_attrs.join(', ') })"

So, any better way to do it? Aside from rewriting execute() to handle arrays the way I want, which I may end up doing.

ralph l mayo
04-01-2007, 08:04 AM
I still don't have a general solution for this but there's a mechanism in DBI that fixes this instance:

Instead of

cursor.execute(l, l + 1, @attrs.values)

You can do

cursor.bind_param(1, l)
cursor.bind_param(2, l + 1)
@attrs.each_with_index { |at, idx|
cursor.bind_param(idx + 3, at[1])

Much better.

11-06-2007, 05:22 PM
ralph l mayo, thanks for reply
code you pasted work fine :)