Accessing Global Variable

Sorry guys,

It’s a simple question but I’m a bit lost:

I’ve the following controller:

class CalendarController < ApplicationController
$srcArray = Array.new

def index
@calendars = Calendar.find(:all)
@calendars.each do |c|
$srcArray = $srcArray << c.name+’&’
end
@iframe = build_iFrame
end

def update_calendar
$srcArray.delete_at(1)
@iframe2 = build_iFrame
end

private
def build_iFrame
src = $srcArray.to_s
src = src.chop
@iframe = ‘blablabla;src=’+src+’;blablabla
return @iframe
end
end

When it’s called it builds a global array based on a DB.
Then it returns a bold string to the View. FINE.

I’ve an ajaxed link_to_remote that calls the function update_calendar.
It’d be supposed to remove the first position of the global array and
return the same bold string without the 1st position. But it returns
nil.

I don’t know what’s the problem since the global array was previously
built.

Thanks for your help.

On Dec 28, 2007, at 10:45 AM, Nuno Machado wrote:

def index
end
When it’s called it builds a global array based on a DB.
Then it returns a bold string to the View. FINE.

I’ve an ajaxed link_to_remote that calls the function update_calendar.
It’d be supposed to remove the first position of the global array and
return the same bold string without the 1st position. But it returns
nil.

I don’t know what’s the problem since the global array was previously
built.

I’ve not used globals very much, but if each call into a controller
is stateless, your global is not surviving. You’d need to write it
into session in order to do what you are suggesting.

Peace,
Phillip

I’ve not used globals very much, but if each call into a controller
is stateless, your global is not surviving. You’d need to write it
into session in order to do what you are suggesting.

Peace,
Phillip

Hi Phillip,

Yes, you’re absolutely right.
Due to the stateless nature of the HTTP protocol, I had to write the
array into a session variable.

Many, many thanks.

On 28 Dec 2007, at 19:14, Nuno Machado wrote:

Hi Phillip,

Yes, you’re absolutely right.
Due to the stateless nature of the HTTP protocol, I had to write the
array into a session variable.

It’s not actually the statelessness of the http protocol: you code
exists in a long running ruby process. However in development mode you
code is reloaded on each request and so your global is reset to
Array.new each time.
Regardless a global is a bad thing to use because you’ve only got one
global but possibly many simultaneous users of your app, so the users
would interfere with each other.

Fred