Is there a notion of a class level “static” code block in Ruby that
would get executed whenever the class is loaded? Basically the
equivalent of Java’s “static {…}” construct?
I don’t necessarily want to put this in an initialize method because
it’s just loading up static data from configuration files.
Or do I have to put the code into an initialize method in my class and
then guard it so that it’s only executed once?
Part I
In order to execute something when the class is loaded you just put it
there
The attr_* methods are a good example, they are executed when the class
statement is executed and their receiver is
of course the class itself.
So that would be like
class Foo
puts “#{self}Bar” @bar = “foo”
…
Part II
def statements are of course defining instance methods so what if we
want
static methods (well there is no such thing), class methods
there are at least 3 options
…
class << self
def static
or
def self.static
or
def Foo.static # not sure if it works is a maintainence nightmare
anyway
!!!
Hope that helps
Robert
–
Deux choses sont infinies : l’univers et la bêtise humaine ; en ce qui
concerne l’univers, je n’en ai pas acquis la certitude absolue.
My irb testing shows me what everyone has said is true.
Thanks for the reminder.
Wes
Matthew D. wrote:
Simon Kröger wrote:
end
#=> Hello
cheers
Simon
I think you need to find out why the class is being loaded multiple
times. I may be completely off base here, but don’t you load your
entire app every time that you get a new request in Rails development
mode? That would explain the results that you’re seeing.
DÅ?a Utorok 11. AprÃl 2006 23:56 Matthew D. napÃsal:
I think you need to find out why the class is being loaded multiple
times. I may be completely off base here, but don’t you load your
entire app every time that you get a new request in Rails development
mode? That would explain the results that you’re seeing.
Does it behave that way for BEGIN {} and END {} blocks too?
Religious sidenote: you should not use “static” code to alter
application
state, lest classloading (-parsing) order static data clobbering grues
eat
your face sooner than you think.
Extract the configuration handling into a singleton initialized from
them
files perhaps?
I think you need to find out why the class is being loaded multiple
times. I may be completely off base here, but don’t you load your
entire app every time that you get a new request in Rails development
mode? That would explain the results that you’re seeing.