Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 8th, 2012  |  syntax: None  |  size: 1.61 KB  |  hits: 15  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1.     def lookup(as_name)
  2.       mycls = self #Class I'm defined in
  3.  
  4.       #We now define the CarType class, as if we were in a file car_type.rb
  5.       cls = Class.new(ActiveRecord::Base) do #Define a new class, extending AR::Base
  6.         #CarType should have the has_many :cars link
  7.         has_many mycls.name.tableize.to_sym
  8.  
  9.         #These are optional. You can define any additional constraints you like.
  10.         validates_uniqueness_of :name
  11.         validates :name, :presence => true
  12.  
  13.         #Methods for using the cache. Providing a second argument saves data into the cache.
  14.         def self.id_for(name, id = nil)
  15.           #We cannot access the class variable for CarType as simply '@@rcaches' because it will
  16.           #look for @@rcaches in the scope of the module we're in.
  17.           class_variable_get(:@@rcaches)[name] ||= id
  18.         end
  19.  
  20.         #This helper method is the "find_or_create" of the class that also
  21.         #updates the cache and the DB.
  22.         def self.gen_id_for(val)
  23.           id = id_for val
  24.           if id.nil?
  25.             #Define this new possible value
  26.             new_db_obj = find_or_create_by_name val
  27.             id_for val, new_db_obj.id
  28.             name_for new_db_obj.id, val
  29.             id = new_db_obj.id
  30.           end
  31.           id
  32.         end
  33.  
  34.         #Query the cache for the value that goes with a certain DB ID
  35.         def self.name_for(id, name = nil)
  36.           class_variable_get(:@@caches)[id] ||= name
  37.         end
  38.       end
  39.  
  40.       #Finally, Bind the created class to a name
  41.       lookup_cls_name = lookup_name.to_s.camelize
  42.       Object.const_set lookup_cls_name, cls #Define it as a global class