Module: DomainNeutral::SymbolizedClass::ClassMethods

Defined in:
lib/domain_neutral/symbolized_class.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args) ⇒ Object

Access like Role.manager

Role.manager
=> Manager role
Same as Role.where(symbol: :manager).first


41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# 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

Instance Method Details

#[](symbol) ⇒ Object

Access descriptor by symbol, e.g.

Role[:manager]
=> Manager role
Same as Role.where(symbol: :manager).first


32
33
34
# File 'lib/domain_neutral/symbolized_class.rb', line 32

def [](symbol)
  find_by_symbol(symbol)
end

#collection(*syms) ⇒ Object

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

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



78
79
80
# File 'lib/domain_neutral/symbolized_class.rb', line 78

def collection(*syms)
  syms.flatten.map { |s| self[s] }
end

#enable_caching(*args) ⇒ Object

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


101
102
103
# 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) ⇒ Object

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



59
60
61
62
63
# File 'lib/domain_neutral/symbolized_class.rb', line 59

def find(id)
  fetch([name, id]) do
    super
  end
end

#find_by_symbol(symbol) ⇒ Object

Find object by symbol

See also

Descriptor[:symbol]
Descriptor.symbol


70
71
72
73
74
# 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