From looking at the docs I can see that it is possible to determine
which Constants have been declared for a particular module, but I cannot
see a means of finding out what constants have been declared in a
particular class.
This leads to ask, if there a method that I can’t see for determining
declared constants in a class? and secondly, is it considered bad
practice to put constants in a class rather than a module?
Rob
-----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World!
-----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =-----
From looking at the docs I can see that it is possible to determine
which Constants have been declared for a particular module, but I cannot
see a means of finding out what constants have been declared in a
particular class.
This leads to ask, if there a method that I can’t see for determining
declared constants in a class?
A class is-a module (i.e. the “Class” class is derived from the “Module”
class). So to determine the constants for a class just call Class#constants.
… and secondly, is it considered bad practice to put constants
in a class rather than a module?
A class is-a module (i.e. the “Class” class is derived from the “Module”
class). So to determine the constants for a class just call
Class#constants.
sigh Thanks Lyle, that was a Doh! moment.
I had tried doing self.constants and had it not work, checked the docs
and then posted the question.
Okay so constants returns an array of the constant names as a string in
short form (i.e. not including the path needed to use them). Hmm, so
with the following sample code, if I want to verify that an method is
passed a valid constant argument what would I want to do? (given the
constant will be passed into the method as a numeric)
example:
module ID3
module V2
class Frame #constants
TRACK_LENGTH = 0
TRACK_TITLE = 1
# … and so on
@frame_id = nil # this objects frame id
def frame_id=(f_id)
@frame_id = f_id if ID3::V2::Frame.constants.include? (f_id)
end # frame
end # v2
end # id3
frame = ID3::V2::Frame.new
the following will fail because the constants returned
are in short from i.e. TRACK_LENGTH and f_id in the method is 0
f.frame_id = ID3::V2::Frame::TRACK_LENGTH
Rob
-----------== Posted via Newsfeed.Com - Uncensored Usenet News ==---------- http://www.newsfeed.com The #1 Newsgroup Service in the World!
-----= Over 100,000 Newsgroups - Unlimited Fast Downloads - 19 Servers =-----
Okay so constants returns an array of the constant names as a string in
short form (i.e. not including the path needed to use them). Hmm, so
with the following sample code, if I want to verify that an method is
passed a valid constant argument what would I want to do? (given the
constant will be passed into the method as a numeric)
Have you considered using constants with a symbolic rather than numeric
value?