Module: Motion::Persistable::ClassMethods

Defined in:
lib/motion/persistable.rb

Instance Method Summary collapse

Instance Method Details

#attr_persisted(method_name, default_value = nil, key_suffix = nil, &block) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/motion/persistable.rb', line 18

def attr_persisted(method_name, default_value = nil, key_suffix = nil, &block)
  callback = block if block_given?

  instance_eval do
        
    define_method method_name do
      if App::Persistence[send("_#{method_name}_key")].nil? and default_value
        App::Persistence[send("_#{method_name}_key")] = default_value
      end          
      App::Persistence[send("_#{method_name}_key")]
    end

    define_method "#{method_name}=" do |value|
      App::Persistence[send("_#{method_name}_key")] = value
      callback.call(value) if callback
      App::Persistence[send("_#{method_name}_key")]
    end

    define_method "_#{method_name}_key" do
      key_suffix = send(key_suffix) if key_suffix.is_a?(Symbol)
      [persistence_key, key_suffix, method_name].compact.join('.')
    end

    private "_#{method_name}_key"

  end
end