Forum: Ruby on Rails class level "static" code in controller object not working

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Bb4bdf2b184027bc38d4fb529770cde5?d=identicon&s=25 Wes Gamble (weyus)
on 2006-04-11 23:33
All,

I have the following code that I put in my controller which I am using
to initialize some static data.  Note that it is not contained with a
method of any kind.

  puts "test"
  config = YAML.load_file("config/config.yml") if config.nil?
  Dir.mkdir(config['html_upload_folder']) unless
File.exist?(config['html_upload_folder'])

I would like this code to only be executed ONCE when the controller
class is loaded but what I am seeing is that every time I invoke a URL
that is related to this controller I see "test" printed on the console.

Which would indicate to me that this code is being executed on each
instantiation of the controller object, not just when the controller
class is loaded.

In irb, the code that's just in a class but not in a method does only
get executed when the class is loaded not when new instances are made.

Is the controller class being reloaded each time?????

Wes

P. S. I am trying to get the equivalent of a Java "static" block here.
Bb4bdf2b184027bc38d4fb529770cde5?d=identicon&s=25 Wes Gamble (weyus)
on 2006-04-12 00:03
It occurs to me that in development mode, the controller class is
reloaded every time isn't it, so does that explain it?

Thanks,
Wes

Wes Gamble wrote:
> All,
>
> I have the following code that I put in my controller which I am using
> to initialize some static data.  Note that it is not contained with a
> method of any kind.
>
>   puts "test"
>   config = YAML.load_file("config/config.yml") if config.nil?
>   Dir.mkdir(config['html_upload_folder']) unless
> File.exist?(config['html_upload_folder'])
>
> I would like this code to only be executed ONCE when the controller
> class is loaded but what I am seeing is that every time I invoke a URL
> that is related to this controller I see "test" printed on the console.
>
> Which would indicate to me that this code is being executed on each
> instantiation of the controller object, not just when the controller
> class is loaded.
>
> In irb, the code that's just in a class but not in a method does only
> get executed when the class is loaded not when new instances are made.
>
> Is the controller class being reloaded each time?????
>
> Wes
>
> P. S. I am trying to get the equivalent of a Java "static" block here.
C9c7a65848f13e2b1a226bbe43bc3672?d=identicon&s=25 Pete Yandell (pete)
on 2006-04-12 01:42
(Received via mailing list)
Yep, that's exactly it.

Pete Yandell
http://9cays.com
This topic is locked and can not be replied to.