Module: ConstantCache::ClassMethods

Defined in:
lib/constant_cache/cache_methods.rb

Instance Method Summary collapse

Instance Method Details

#cache_constants(opts = {}) ⇒ 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 or DataMapper::Resource.

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
  include ConstantCache

  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.



43
44
45
46
47
48
49
50
51
# File 'lib/constant_cache/cache_methods.rb', line 43

def cache_constants(opts = {})
  key = opts.fetch(:key, :name)
  limit = opts.fetch(:limit, CHARACTER_LIMIT)
  limit = CHARACTER_LIMIT unless limit > 0

  @cache_options = {:key => key, :limit => limit}

  all.each {|instance| instance.set_instance_as_constant }
end

#cache_optionsObject



53
54
55
# File 'lib/constant_cache/cache_methods.rb', line 53

def cache_options
  @cache_options
end