0
+ # Generated constant conflicts with an existing constant
0
class DuplicateConstantError < StandardError; end
0
- class InvalidLimitError < StandardError; end
0
+ class InvalidLimitError < StandardError #:nodoc:
0
+ module CacheMethods
#:nodoc:0
+ # The caches_constants method is the core of the functionality behind this mix-in. It provides
0
+ # a simple interface to cache the data in the corresponding table as constants on the model:
0
+ # It makes certain assumptions about your schema: the constant created is based off of a <tt>name</tt>
0
+ # column in the database and long names are truncated to ConstantCache::CHARACTER_LIMIT characters before
0
+ # being set as constants. If there is a 'Pending' status in the database, you will now have a
0
+ # Status::PENDING constant that points to an instance of ActiveRecord.
0
+ # Beyond the basics, some configuration is allowed. You can change both the column that is used to generate
0
+ # the constant and the truncation length:
0
+ # caches_constants :key => :abbreviation, :limit => 2
0
+ # This will use the <tt>abbreviation</tt> column to generate constants and will truncate constant names to 2
0
+ # characters at the maximum.
0
+ # Note: In the event that a generated constant conflicts with an existing constant, a
0
+ # ConstantCache::DuplicateConstantError is raised.
0
def caches_constants(additional_options = {})
0
cattr_accessor :cache_options
0
- self.cache_options = {:key => :name, :limit =>
64}.merge(additional_options)
0
+ self.cache_options = {:key => :name, :limit =>
ConstantCache::CHARACTER_LIMIT}.merge(additional_options)
0
raise ConstantCache::InvalidLimitError, "Limit of #{self.cache_options[:limit]} is invalid" if self.cache_options[:limit] < 1
0
find(:all).each {|model| model.set_instance_as_constant }
0
+ def constant_name
#:nodoc:0
constant_name = self.send(self.class.cache_options[:key].to_sym).constant_name
0
constant_name = constant_name[0, self.class.cache_options[:limit]] unless constant_name.blank?
0
+ private :constant_name
0
+ # Create a constant on the class that pointing to an instance
0
def set_instance_as_constant
0
- raise ConstantCache::DuplicateConstantError, "Constant #{self.class.to_s}::#{const} has already been defined" if self.class.const_defined?(const)
0
+ if self.class.const_defined?(const)
0
+ message = "Constant #{self.class.to_s}::#{const} has already been defined"
0
+ raise ConstantCache::DuplicateConstantError, message
0
self.class.const_set(const, self) if !const.blank?
Comments
No one has commented yet.