Module: Amfetamine::QueryMethods::ClassMethods
- Defined in:
- lib/amfetamine/query_methods.rb
Instance Method Summary collapse
- #all(opts = {}) ⇒ Object
- #cache_conditions(key, condition = nil) ⇒ Object
- #clean_cache! ⇒ Object
- #create(args = {}) ⇒ Object
- #find(id, opts = {}) ⇒ Object
- #get_data(key, conditions = nil, method = :get) ⇒ Object
- #recent_cache_key ⇒ Object
Instance Method Details
#all(opts = {}) ⇒ Object
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/amfetamine/query_methods.rb', line 32 def all(opts={}) begin key = opts[:nested_path] || self.rest_path data = get_data(key, opts[:conditions]) if data[:status] == :success vals = data[:body].compact.map { |d| build_object(d) } else [] end rescue clean_cache! raise end end |
#cache_conditions(key, condition = nil) ⇒ Object
48 49 50 51 52 53 54 55 56 57 |
# File 'lib/amfetamine/query_methods.rb', line 48 def cache_conditions(key, condition=nil) return nil unless condition conditions = cache.get("#{key}_conditions") || [] q_condition = condition.to_query if !conditions.include?(q_condition) conditions << condition.to_query cache.set("#{key}_conditions", conditions) end end |
#clean_cache! ⇒ Object
84 85 86 87 88 89 90 91 92 93 |
# File 'lib/amfetamine/query_methods.rb', line 84 def clean_cache! if cacheable? cache.delete(rest_path) condition_keys = cache.get("#{rest_path}_conditions") || [] condition_keys.each do |cc| cache.delete(rest_path + cc) end Amfetamine.logger.info "Cleaned cache for #{self.model_name}" end end |
#create(args = {}) ⇒ Object
59 60 61 62 63 |
# File 'lib/amfetamine/query_methods.rb', line 59 def create(args={}) self.new(args).tap do |obj| obj.run_callbacks(:create) { obj.save } end end |
#find(id, opts = {}) ⇒ Object
17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/amfetamine/query_methods.rb', line 17 def find(id, opts={}) begin key = opts[:nested_path] || self.find_path(id) data = get_data(key, opts[:conditions]) if data[:status] == :success val = build_object(data[:body]) else nil end rescue clean_cache! raise end end |
#get_data(key, conditions = nil, method = :get) ⇒ Object
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
# File 'lib/amfetamine/query_methods.rb', line 65 def get_data(key, conditions=nil, method=:get) if cacheable? if conditions @recent_cache_key = key + conditions.to_query cache_conditions(key, conditions) else @recent_cache_key = key end Amfetamine.logger.info "Fetching object from cache: #{@recent_cache_key}" cache.fetch(@recent_cache_key) do Amfetamine.logger.info "Miss! #{@recent_cache_key}" handle_request(method, key, { :query => conditions } ) end else handle_request(method,key, { :query => conditions }) end end |
#recent_cache_key ⇒ Object
13 14 15 |
# File 'lib/amfetamine/query_methods.rb', line 13 def recent_cache_key @recent_cache_key end |