Class: Seamless::Model

Inherits:
ActiveRecord::Base show all
Defined in:
lib/seamless/model.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from ActiveRecord::Base

#to_json

Class Method Details

.find_by_sql(*args) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/seamless/model.rb', line 37

def find_by_sql(*args)

	return super(args) if not defined?(Cache)
	return super(args) unless CachedModel.use_memcache? or CachedModel.use_local_cache?
		
	# don't cache result of :all
	return super(args) if args.first =~ /^SELECT \* FROM #{table_name}$/
	
	# don't do more complex finds
	case args.first
		when Array then
			return super(args)
		end
		
	# some SQL ends with space
	sql = args.first.chomp!(" ")
	log "SQL: #{sql}"
		
	if @model_regex==nil
		@model_regex = /^SELECT \* FROM #{table_name} WHERE \(#{table_name}\.`#{primary_key}` = (\d+)\)$/
	end
	
	# see if this is a single query for the primary key
	match = @model_regex.match(sql)
	pk = nil
	
	if match
		# extract the primary key
		pk = match[1]	
		
		# check to see if the record is in the DB with PK
		if CachedModel.use_memcache?
			result = Cache.get "#{name}:id:#{pk}"
			if result
				log "cache hit: #{name}.#{primary_key} -> #{pk}"
				result.instance_variable_set(:@new_record,false)
				return [result]
			else
				log "cache miss: #{name}.#{primary_key} -> #{pk}"
			end
		end
	end
	
	records = super(args)
	
	if CachedModel.use_memcache?
		# store in cache
		if pk
			Cache.put "#{name}:id:#{pk}", records.first, CachedModel.ttl
			log "cache set: #{name}.#{primary_key} -> #{pk}"
		end
	end
	
	records
end

.log(msg) ⇒ Object



31
32
33
34
35
# File 'lib/seamless/model.rb', line 31

def log(msg)
	if logger && logger.level == Logger::DEBUG
		logger.add(Logger::DEBUG, "Seamless::Model - #{msg}")
	end
end

.modelsObject



9
10
11
# File 'lib/seamless/model.rb', line 9

def Model.models
	SEAMLESS_MODELS
end

Instance Method Details

#destroyObject



18
19
20
21
# File 'lib/seamless/model.rb', line 18

def destroy
	super
	delete_cache if defined?(Cache)
end

#updateObject



13
14
15
16
# File 'lib/seamless/model.rb', line 13

def update
	super
	delete_cache if defined?(Cache)
end