module DomainNeutral::SymbolizedClass::ClassMethods

Public Instance Methods

[](symbol) click to toggle source

Access descriptor by symbol, e.g.

Role[:manager]
=> Manager role
Same as Role.where(symbol: :manager).first
# File lib/domain_neutral/symbolized_class.rb, line 32
def [](symbol)
  find_by_symbol(symbol)
end
collection(*syms) click to toggle source

Role.collection(:site_admin, :user_admin, :admin)

> Role[] consisting of Role.site_admin, Role.user_admin, Role.admin

# File lib/domain_neutral/symbolized_class.rb, line 78
def collection(*syms)
  syms.flatten.map { |s| self[s] }
end
enable_caching(*args) click to toggle source

Turn cache on or off Calling enable_caching without parameter or true will turn on caching By default cache is off.

Example - enabling caching

class MySymbolizedClass < ActiveRecord::Base
  include DomainNeutral::SymbolizedClass
  enable_caching
  ...
end

Example - disable caching

class MySymbolizedClass < ActiveRecord::Base
  include DomainNeutral::SymbolizedClass
  enable_caching false
  ...
end
# File lib/domain_neutral/symbolized_class.rb, line 101
def enable_caching(*args)
  self.caching_enabled = args.size > 0 ? args.first : true
end
find(id) click to toggle source

Overrides find by using cache. The key in cache is [class_name, id] or ':class_name/:id', e.g. 'Role/1'

Calls superclass method
# File lib/domain_neutral/symbolized_class.rb, line 59
def find(id)
  fetch([name, id]) do
    super
  end
end
find_by_symbol(symbol) click to toggle source

Find object by symbol

See also

Descriptor[:symbol]
Descriptor.symbol
# File lib/domain_neutral/symbolized_class.rb, line 70
def find_by_symbol(symbol)
  fetch([name, symbol.to_s]) do
    where(symbol: symbol).first
  end
end
method_missing(method, *args) click to toggle source

Access like Role.manager

Role.manager
=> Manager role
Same as Role.where(symbol: :manager).first
Calls superclass method
# File lib/domain_neutral/symbolized_class.rb, line 41
def method_missing(method, *args)
  begin
    if method != :find_by_symbol
      if obj = find_by_symbol(method)
        redefine_method method do
          find_by_symbol(method)
        end
        return obj
      end
    end
  rescue
    # Ignore errors, and call super
  end
  super
end

Private Instance Methods

fetch(key, options = nil) { || ... } click to toggle source

Ensures cache is cleared if nil result

# File lib/domain_neutral/symbolized_class.rb, line 107
def fetch(key, options = nil) 
  if caching_enabled
    result = Rails.cache.fetch(key, options) do
      yield
    end
    Rails.cache.delete(key) unless result
  else
    result = yield
  end
  result
end