You see, there's stuff that need to be donne in both cases, in instances
and in classes. For example:
class SomeClass
=A0def self.method
=A0 =A0if file_exists?
=A0 =A0 =A0#do stuff
=A0 =A0end
=A0 =A0#something need to be donne here, and I need to check if the file
exists
=A0 =A0#I dont want to define a nother class method exactly the same as t= he
already declared instance method.
=A0end
Since file_exists? is an instance method, it is very likely to return
true/false based on the state of the instance (see below). Calling
file_exists in self.method does not make sense unless its
responsibility is to act on an instance of your class - like a
factory, or processing an instance passed to it as a parameter.
def self.method(object)
if object.file_exists?
# do something on that object
object.statistics
end
end
or,
def self.create(*args)
object =3D SomeClass.new(*args)
return object if object.file_exists?
end
=A0def file_exists?
=A0 =A0#there are instance methods depending on this one
=A0 =A0File.exists?("some_file_name.txt")
=A0end
Umm, is the file name hard coded, or does it depend on the state of
the instance, like:
def file_exists?
File.exists?(@file)
end
If it is hard coded, or depends on a constant, you might as well
define a class method:
class SomeClass
CONFIG =3D "~/.foo.rc"
def self.config_exists?
File.exists?(CONFIG)
end
def init
raise "Config file not found" unless SomeClass.config_exists?
...
end
end
How do you deal with this kind of thing?
Depends on the context.
--=20
Anurag Priyam
http://about.me/yeban/