Module: ConstantCache::ClassMethods

Defined in:
lib/constant_cache/cache_methods.rb

Instance Method Summary collapse

Instance Method Details

#cache!Object



65
66
67
68
69
# File 'lib/constant_cache/cache_methods.rb', line 65

def cache!
  unless DataMapper::Repository.adapters.empty?
    all.each {|instance| instance.set_instance_as_constant }
  end
end

#cache_as(key) ⇒ 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
  include ConstantCache
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

  cache_as :abbreviation
  cache_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.



49
50
51
# File 'lib/constant_cache/cache_methods.rb', line 49

def cache_as(key)
  self.cache_options[:key] = key
end

#cache_limit(limit) ⇒ Object



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

def cache_limit(limit)
  self.cache_options[:limit] = (limit > 0 ? limit : CHARACTER_LIMIT)
end

#cache_optionsObject



57
58
59
# File 'lib/constant_cache/cache_methods.rb', line 57

def cache_options
  @cache_options ||= {:key => :name, :limit => CHARACTER_LIMIT}
end

#reset_cache_optionsObject



61
62
63
# File 'lib/constant_cache/cache_methods.rb', line 61

def reset_cache_options
  @cache_options = {:key => :name, :limit => CHARACTER_LIMIT}
end