Module: MongoMethodStorable

Defined in:
lib/mongo_method_storable.rb,
lib/mongo_method_storable/version.rb

Overview

require “mongoid/attributes”

Defined Under Namespace

Classes: AlreadyAliasedError

Constant Summary collapse

MONGO_STORE_PREFIX =
'_old_mstore_'
VERSION =
"0.0.1"

Instance Method Summary collapse

Instance Method Details

#mongo_store(method_name) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/mongo_method_storable.rb', line 7

def mongo_store(method_name)
  old_method_name = "#{MONGO_STORE_PREFIX + method_name.to_s}".to_sym
  raise AlreadyAliasedError.new("Already aliased #{method_name}") if method_defined?(old_method_name)
  alias_method old_method_name, method_name

  if instance_method(method_name).arity == 0
    define_method method_name do
      attr_val = read_attribute method_name
      return attr_val if attr_val
      attr_val = send old_method_name
      write_attribute(method_name, attr_val)
      save!
      attr_val
    end
  else
    # deal with this case when I need to
  end
end

#storable_methodsObject



26
27
28
29
30
# File 'lib/mongo_method_storable.rb', line 26

def storable_methods
  self.instance_methods.
    select {|m| self.instance_method(m).name.to_s.start_with? MONGO_STORE_PREFIX}.
    map {|m| m.slice(MONGO_STORE_PREFIX.length..m.length).to_sym}
end