Module: Persistent::Settings::ClassMethods

Includes:
Caching, Persistance
Defined in:
lib/persistent/settings.rb

Constant Summary collapse

@@mutex =
Mutex.new
@@accessors =
[]

Instance Method Summary collapse

Methods included from Persistance

#load_from_persistance, #load_from_persistance!, #persist, #read_from_persistance

Methods included from Caching

#cache_key_for, #read_from_cache, #write_to_cache

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args) ⇒ Object



20
21
22
23
24
25
26
27
28
29
# File 'lib/persistent/settings.rb', line 20

def method_missing(method_name, *args)
  if assignation?(method_name)
    self.define_setter_and_getter(method_name)
    self.send(method_name, args.first)
  elsif accessors.include?(method_name)
    nil
  else
    super
  end
end

Instance Method Details

#accessorsObject



65
66
67
# File 'lib/persistent/settings.rb', line 65

def accessors
  @@accessors
end

#assignation?(method_name) ⇒ Boolean

Returns:

  • (Boolean)


53
54
55
# File 'lib/persistent/settings.rb', line 53

def assignation?(method_name)
  method_name.to_s.match(/=$/)
end

#define_setter_and_getter(method_name) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/persistent/settings.rb', line 31

def define_setter_and_getter(method_name)
  getter = method_name.to_s.chop

  (class << self; self; end).instance_eval do
    define_method method_name do |value|
      @@mutex.synchronize do
        persist(getter, value)
        write_to_cache getter, value
      end
    end

    define_method getter do
      value = read_from_cache getter
      unless value
        value = read_from_persistance getter
        write_to_cache getter, value
      end
      value
    end
  end
end

#keysObject



61
62
63
# File 'lib/persistent/settings.rb', line 61

def keys
  self.select(:var).collect { |s| s.var.to_sym }
end

#ready?Boolean

Returns:

  • (Boolean)


57
58
59
# File 'lib/persistent/settings.rb', line 57

def ready?
  connected? && table_exists?
end