Skip to content

Instantly share code, notes, and snippets.

@Nimster
Created August 6, 2011 06:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Nimster/1129091 to your computer and use it in GitHub Desktop.
Save Nimster/1129091 to your computer and use it in GitHub Desktop.
Rails lookup v2 - Create the lookup type
def lookup(as_name)
mycls = self #Class I'm defined in
#We now define the CarType class, as if we were in a file car_type.rb
cls = Class.new(ActiveRecord::Base) do #Define a new class, extending AR::Base
#CarType should have the has_many :cars link
has_many mycls.name.tableize.to_sym
#These are optional. You can define any additional constraints you like.
validates_uniqueness_of :name
validates :name, :presence => true
#Methods for using the cache. Providing a second argument saves data into the cache.
def self.id_for(name, id = nil)
#We cannot access the class variable for CarType as simply '@@rcaches' because it will
#look for @@rcaches in the scope of the module we're in.
class_variable_get(:@@rcaches)[name] ||= id
end
#This helper method is the "find_or_create" of the class that also
#updates the cache and the DB.
def self.gen_id_for(val)
id = id_for val
if id.nil?
#Define this new possible value
new_db_obj = find_or_create_by_name val
id_for val, new_db_obj.id
name_for new_db_obj.id, val
id = new_db_obj.id
end
id
end
#Query the cache for the value that goes with a certain DB ID
def self.name_for(id, name = nil)
class_variable_get(:@@caches)[id] ||= name
end
end
#Finally, Bind the created class to a name
lookup_cls_name = lookup_name.to_s.camelize
Object.const_set lookup_cls_name, cls #Define it as a global class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment