This is the old RCRchive. It's available only for reading and reference. To submit RCRs for Ruby 1.9/2.0, and to participate in discussions about them, please visit the new RCRchive.
ruby picture

RCR 343: Make class constants less cumbersome

Submitted by Ondrej Bilka (Thu Aug 17 15:16:52 UTC 2006)

Abstract

Problem is that using class constants outside lead to too long code. Consider Process::RLIMIT_CORE. It has 20 charcters. I decided use enum-like construction for it.

Problem

Problem is that long names discourage to use them. Obvious solutions are write 24574 istead const or include all to Kernel. Another issue is that all constants are put to basic class although adding to subclasses would be more sensible

Proposal

Another enum implementation. Where constant is expected you can use symbol with its name istead. Enum-slyle is that array of symbols will be considered as ored constants. before File.new("foo",File::RDWR | File::LOCK_EX | File::SYNC) after File.new("foo",[:RDWR,:LOCK_EX,:SYNC])

Analysis

Disadvantage is that it would be slower. Advantage is that it will be safer and constants could be split to apropriate subclass. To be efective and consistent you must replace all vars which affect to new style by adding var=constvalue(var).

Implementation

def constvalue(consts,klass=this.class)
   if consts.is_a? Array
     return consts.inject(0){|i,j| i|klass.con_get(j)}
  else
     klass.const_get(consts)
end;end def const_get(cons)
  return cons if cons.is_a? Numeric
  old_const_get(cons)
end
ruby picture
Comments Current voting
I'm afraid this doesn't make sense. What if I want to send an array of symbols? I don't want them automatically turned into constants -- let alone constants from another nesting.

David Black


It would be better IMHO if methods like File.new just handled symbol options.

  File.new( "foo", :rdwr, :lock, :sync )

or perhaps la Rails

  File.new "foo", :options => [:rdwr, :lock, :sync]

7rans


How about "Type error: Can't convert Array into Fixnum."

(Unless you write function that accepts as flag Fixnum, Array, Hash, Kernel, Date, Pizza classes AND use constvalue to convert )

Who said that conversion is automatic? Only when you use constvalue() conversion is done. Otherwise you should use const_get


Great 7rans you should write patch (C equivalent of this) def File.new(a,*flags) f=0 flags.each{|flag| case flag f|=RDWR when :rdwr f|=SYNC when :sync f|=RWONLY when :rwonly ... else raise "misspelled flag" }

Ondrej Bilka


Strongly opposed1
Opposed6
Neutral0
In favor0
Strongly advocate0
ruby picture
ruby picture

Powered by Ruby on Rails.