Module: ConstantCache::CacheMethods::ClassMethods
- Defined in:
- lib/constant_cache/cache_methods.rb
Instance Method Summary collapse
-
#caches_constants(additional_options = {}) ⇒ Object
The caches_constants method is the core of the functionality behind this mix-in.
Instance Method Details
#caches_constants(additional_options = {}) ⇒ Object
The caches_constants method is the core of the functionality behind this mix-in. It provides a simple interface to cache the data in the corresponding table as constants on the model:
class Status
caches_constants
end
It makes certain assumptions about your schema: the constant created is based off of a name column in the database and long names are truncated to ConstantCache::CHARACTER_LIMIT characters before being set as constants. If there is a ‘Pending’ status in the database, you will now have a Status::PENDING constant that points to an instance of ActiveRecord.
Beyond the basics, some configuration is allowed. You can change both the column that is used to generate the constant and the truncation length:
class State
caches_constants :key => :abbreviation, :limit => 2
end
This will use the abbreviation column to generate constants and will truncate constant names to 2 characters at the maximum.
Note: In the event that a generated constant conflicts with an existing constant, a ConstantCache::DuplicateConstantError is raised.
42 43 44 45 46 47 48 49 |
# File 'lib/constant_cache/cache_methods.rb', line 42 def caches_constants( = {}) cattr_accessor :cache_options self. = {:key => :name, :limit => ConstantCache::CHARACTER_LIMIT}.merge() raise ConstantCache::InvalidLimitError, "Limit of #{self.[:limit]} is invalid" if self.[:limit] < 1 find(:all).each {|model| model.set_instance_as_constant } end |