Module: ActiveRecord::Acts::Constant::ClassMethods

Defined in:
lib/acts_as_constant.rb

Instance Method Summary collapse

Instance Method Details

#acts_as_constant(col = :name) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/acts_as_constant.rb', line 10

def acts_as_constant(col = :name)
  begin
    #puts self.to_s
    
    # let's set up a variable to represent the name of the klass
    const = self.to_s
    
    # create a constant array to hold the values
    # create a nice get method to pull from the constant array
    class_eval %{
      private
      #{const.upcase}_CONSTANTS = []
      
      public
      def self.get(id)
        return nil if id.blank?
        #{const.upcase}_CONSTANTS[id]
      end
      
      def self.CONSTANTS
        #{const.upcase}_CONSTANTS
      end
    }                     
    
    # let's build methods for everything in the database.
    Module.const_get(const).find(:all).each do |rec|
      #puts rec.inspect
      name = rec.send(col)
      
      unless name.nil?
        
        # let's sanitize the name a bit.
        name = name.downcase
        name = name.gsub(' ', '_')                                                                        
        
        # let's create two methods an all downcase method for accessing the constant and an upper case one
        class_eval %{
          # by using .freeze we can prevent the object from being modified.
          #{const.upcase}_CONSTANTS[#{rec.id}] = rec.freeze
          
          def self.#{name}
            #{const.upcase}_CONSTANTS[#{rec.id}]
          end
          
          def self.#{name.upcase}
            #{const.upcase}_CONSTANTS[#{rec.id}]
          end
        }
      end
    end
    class_eval %{
      # by using .freeze we can prevent the constants array from being modified.
      #{const.upcase}_CONSTANTS.freeze
    }
  rescue => ex
  end
  
end