Module: ShadowModel::Extension::ClassMethods

Defined in:
lib/shadow_model/extension.rb

Instance Method Summary collapse

Instance Method Details

#build_shadow_cache_key(id) ⇒ Object



123
124
125
# File 'lib/shadow_model/extension.rb', line 123

def build_shadow_cache_key(id)
  "#{self.name.tableize}:Shadow:#{id}"
end

#define_shadow_attributes(attribute_name) ⇒ Object



81
82
83
84
85
86
87
88
89
90
91
# File 'lib/shadow_model/extension.rb', line 81

def define_shadow_attributes(attribute_name)
  self.class_eval "    def \#{attribute_name}_without_shadow\n      self.read_attribute(:\#{attribute_name})\n    end\n\n    def \#{attribute_name}\n      shadow_model? ? shadow_data[:\#{attribute_name}] : \#{attribute_name}_without_shadow\n    end\n  RUBY\nend\n"

#define_shadow_methods(method_name) ⇒ Object



93
94
95
96
97
98
99
100
101
102
# File 'lib/shadow_model/extension.rb', line 93

def define_shadow_methods(method_name)
  if self.shadow_keys.include?(method_name.to_sym) && !self.instance_methods.include?("#{method_name}_without_shadow".to_sym)
    self.class_eval "      def \#{method_name}_with_shadow\n        shadow_model? ? shadow_data[:\#{method_name}] : \#{method_name}_without_shadow\n      end\n      alias_method_chain :\#{method_name}, :shadow\n    RUBY\n  end\nend\n"

#find_by_shadow(id) ⇒ Object



104
105
106
107
108
109
110
111
112
113
114
115
116
# File 'lib/shadow_model/extension.rb', line 104

def find_by_shadow(id)
  if shadow_data = find_shadow_data(id)
    instance = self.new
    instance.shadow_model = true
    instance.shadow_data = shadow_data
    instance.readonly!
    instance
  else
    instance = self.find(id)
    instance.update_shadow_cache
    find_by_shadow(id)
  end
end

#find_shadow_data(id) ⇒ Object



118
119
120
121
# File 'lib/shadow_model/extension.rb', line 118

def find_shadow_data(id)
  data = Redis.current.get(build_shadow_cache_key(id))
  data ? Marshal.load(data) : nil
end

#method_added(method_name) ⇒ Object



77
78
79
# File 'lib/shadow_model/extension.rb', line 77

def method_added(method_name)
  define_shadow_methods(method_name)
end

#set_shadow_keys(args, options = {}) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'lib/shadow_model/extension.rb', line 59

def set_shadow_keys(args, options = {})
  @shadow_attributes ||= []
  @shadow_methods ||= []
  self.shadow_options = options
  args.each do |arg|
    if self.attribute_names.include?(arg.to_s)
      @shadow_attributes << arg.to_sym
    else
      @shadow_methods << arg.to_sym
    end
  end
  @shadow_attributes.each { |attr| define_shadow_attributes(attr) }
end

#shadow_keysObject



73
74
75
# File 'lib/shadow_model/extension.rb', line 73

def shadow_keys
  @shadow_attributes + @shadow_methods
end