Module: TinyCache::ActiveRecord::FinderMethods

Extended by:
ActiveSupport::Concern
Defined in:
lib/tiny_cache/active_record/finder_methods.rb

Instance Method Summary collapse

Instance Method Details

#find_by_attributes(match, attributes, *args) ⇒ Object

TODO:



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/tiny_cache/active_record/finder_methods.rb', line 17

def find_by_attributes(match, attributes, *args)
  conditions = Hash[attributes.map {|a| [a, args[attributes.index(a)]]}]
  result = where(conditions).send(match.finder)

  if match.bang? && result.nil?
    raise RecordNotFound, "Couldn't find #{@klass.name} with #{conditions.to_a.collect {|p| p.join(' = ')}.join(', ')}"
  else
    yield(result) if block_given?
    result
  end
end

#find_by_attributes_with_tiny_cache(match, attributes, *args) ⇒ Object

TODO cache find_or_create_by_id



69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/tiny_cache/active_record/finder_methods.rb', line 69

def find_by_attributes_with_tiny_cache(match, attributes, *args)
  return find_by_attributes_without_tiny_cache(match, attributes, *args) unless tiny_cache_enabled?
  return find_by_attributes_without_tiny_cache(match, attributes, *args) unless select_all_column?

  conditions = Hash[attributes.map {|a| [a, args[attributes.index(a)]]}]

  if conditions.has_key?("id")
    result = wrap_bang(match.bang?) do
      if conditions.size == 1
        find_one_with_tiny_cache(conditions["id"])
      else
        where(conditions.except("id")).find_one_with_tiny_cache(conditions["id"])
      end
    end

    yield(result) if block_given? #edge rails do this bug rails3.1.0 not

    return result
  end

  find_by_attributes_without_tiny_cache(match, attributes, *args)
end

#find_one_with_tiny_cache(id) ⇒ Object

TODO fetch multi ids

Cacheable:

current_user.articles.where(:status => 1).visiable.find(params[:id])

Uncacheable:

Article.where("user_id = '1'").find(params[:id])
Article.where("user_id > 1").find(params[:id])
Article.where("articles.user_id = 1").find(prams[:id])
Article.where("user_id = 1 AND ...").find(params[:id])


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
# File 'lib/tiny_cache/active_record/finder_methods.rb', line 41

def find_one_with_tiny_cache(id)
  return find_one_without_tiny_cache(id) unless tiny_cache_enabled?
  return find_one_without_tiny_cache(id) unless select_all_column?

  id = id.id if ActiveRecord::Base === id

  # if ::ActiveRecord::IdentityMap.enabled? && cachable? && record = from_identity_map(id)
  #   return record
  # end

  if cachable?
    if record = @klass.read_tiny_cache(id)
      return record 
    end
  end

  if cachable_without_conditions?
    if record = @klass.read_tiny_cache(id)
      return record if where_match_with_cache?(where_values, record)
    end
  end

  record = find_one_without_tiny_cache(id)
  record.write_tiny_cache
  record
end