Method: Sequel::Plugins::StaticCache::ClassMethods#as_hash

Defined in:
lib/sequel/plugins/static_cache.rb

#as_hash(key_column = nil, value_column = nil, opts = OPTS) ⇒ Object

Use the cache instead of a query to get the results.

[View source]

147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/sequel/plugins/static_cache.rb', line 147

def as_hash(key_column = nil, value_column = nil, opts = OPTS)
  if key_column.nil? && value_column.nil?
    if @static_cache_frozen && !opts[:hash]
      return Hash[cache]
    else
      key_column = primary_key
    end
  end

  h = opts[:hash] || {}
  if value_column
    if value_column.is_a?(Array)
      if key_column.is_a?(Array)
        @all.each{|r| h[r.values.values_at(*key_column)] = r.values.values_at(*value_column)}
      else
        @all.each{|r| h[r[key_column]] = r.values.values_at(*value_column)}
      end
    else
      if key_column.is_a?(Array)
        @all.each{|r| h[r.values.values_at(*key_column)] = r[value_column]}
      else
        @all.each{|r| h[r[key_column]] = r[value_column]}
      end
    end
  elsif key_column.is_a?(Array)
    @all.each{|r| h[r.values.values_at(*key_column)] = static_cache_object(r)}
  else
    @all.each{|r| h[r[key_column]] = static_cache_object(r)}
  end
  h
end