Suppose I have a ruby file with a single class. Is it
possible to write a
ruby script that can extract the class name from the file?
[…]
Is it possible to extract the class name via reflection?
Well, here’s one terrible idea. (It’s ‘terrible’ because it’s brittle,
and only works if no other files defining new classes have been defined,
and will break if a new Ruby release defines a new class.)
BUILTIN_CLASSES = %w| ArgumentError Array Bignum Binding Class
Continuation
Data Date DateTime Dir EOFError Exception FalseClass File Fixnum Float
FloatDomainError Hash IO IOError IndexError Integer Interrupt LoadError
LocalJumpError MatchData MatchData Method Module NameError NilClass
NoMemoryError NoMethodError NotImplementedError Numeric Object Proc
Range
RangeError Rational Regexp RegexpError RuntimeError ScriptError
SecurityError SignalException StandardError String Struct Symbol
SyntaxError SystemCallError SystemExit SystemStackError Thread
ThreadError ThreadGroup Time TrueClass TypeError UnboundMethod
ZeroDivisionError |.map{ |n| Object.const_get( n ) }
class Foo; end
nonstandard_classes = Object.constants.map{ |name|
klass = Object.const_get( name )
Class === klass ? klass : nil
}.compact - BUILTIN_CLASSES
Well, here’s one terrible idea. (It’s ‘terrible’ because it’s brittle,
and only works if no other files defining new classes have been defined,
and will break if a new Ruby release defines a new class.)
Suppose I have a ruby file with a single class. Is it
possible to write a
ruby script that can extract the class name from the file?
[…]
Is it possible to extract the class name via reflection?
Well, here’s one terrible idea. (It’s ‘terrible’ because it’s brittle,
and only works if no other files defining new classes have been defined,
and will break if a new Ruby release defines a new class.)
I agree.
I just wanted to share what I had in mind, which will not break because
of a new ruby version (I guess):
old_classes = self.class.constants.find_all {|x|
self.class.const_get(x).class == Class }.compact
require’my_lib’
all_classes = self.class.constants.find_all {|x|
self.class.const_get(x).class == Class }.compact