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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# 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
    klass = self.to_s
    #puts "klass = #{klass}"
    const = klass.upcase.gsub("::", "_")
    #puts "const = #{const}"
    
    define_method("constantize") do
      self.send(col).constantize
    end
    
    class_eval %{
      def self.constant_class_name
        "#{const}"
      end
      
      def self.constant_column
        "#{col}"
      end
    }
    
    # create a constant array to hold the values
    # create a nice get method to pull from the constant array
    class_eval %{
      private
      #{self.constant_class_name}_CONSTANTS = []
      
      public
      def self.get(id)
        return nil if id.blank?
        #{self.constant_class_name}_CONSTANTS[id]
      end
      
      def self.CONSTANTS
        #{self.constant_class_name}_CONSTANTS
      end

    }
    
    class_eval do
      def self.reload_constants!
        begin
          self.CONSTANTS.clear
          
          rows = eval "#{self.to_s}.find(:all)"

          rows.each do |rec|
            #puts rec.inspect
            name = rec.send(self.constant_column)

            unless name.nil?

              # let's sanitize the name a bit.
              name = name.underscore.gsub("/", '_')

              self.instance_eval do

                define_method("constant_name") do
                  self.send(self.constant_column).downcase.gsub(' ', '_')
                end

              end                                                                        

              # 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.
                #{self.constant_class_name}_CONSTANTS[#{rec.id}] = rec.freeze

                def self.#{name}
                  #{self.constant_class_name}_CONSTANTS[#{rec.id}]
                end

                def self.#{name.upcase}
                  #{self.constant_class_name}_CONSTANTS[#{rec.id}]
                end
              }
            end
          end
        rescue Exception => e
          
        end
        
      end
    end
    
    self.reload_constants!
    
  rescue => ex
    #puts "Error in acts_as_constant: #{ex.message}"
    #puts ex.backtrace
  end
  
end