Skip to content

Instantly share code, notes, and snippets.

@xn
Forked from lypborges/Findable.rb
Last active Feb 3, 2016
Embed
What would you like to do?
Create a concern to use when using uuid as default primary key

When you use uuid some methods stop to work as expected. Using this concern in your models will do the job. All you need to do is:

1 - Copy this file to models/concerns 2 - In all your models use this concern just, like this

class Client < ActiveRecord::Base
	include Findable
end
module Findable
extend ActiveSupport::Concern
# When you use uuid some methods stop to work as expected. Using this concern in your models will do the job.
# Override methods on module FinderMethods that use id as default order when no order is defined
# It's a working in progress
# referencer:
# http://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-take
# https://github.com/rails/rails/blob/f52354ad1d15120dcc5284714bee7ee3f052986c/activerecord/lib/active_record/relation/finder_methods.rb#L503
module ClassMethods
def first(limit = nil)
self.order("created_at").first(limit)
end
def first!
self.order("created_at").first!
end
def second
self.order("created_at").second
end
def second!
self.order("created_at").second!
end
def third
self.order("created_at").third
end
def third!
self.order("created_at").third!
end
def fourth
self.order("created_at").fourth
end
def fourth!
self.order("created_at").fourth!
end
def fifth
self.order("created_at").fifth
end
def fifth!
self.order("created_at").fifth!
end
def forty_two
self.order("created_at").forty_two
end
def forty_two!
self.order("created_at").forty_two!
end
def last(limit = nil)
self.order("created_at DESC").last(limit)
end
def last!
self.order("created_at DESC").last!
end
def find_in_batches(options = {})
options.assert_valid_keys(:start, :batch_size)
relation = self
start = options[:start]
batch_size = options[:batch_size] || 1000
unless block_given?
return to_enum(:find_in_batches, options) do
total = start ? where(table['created_at'].gteq(start)).size : size
(total - 1).div(batch_size) + 1
end
end
if logger && (all.orders.present? || all.taken.present?)
logger.warn("Scoped order and limit are ignored, it's forced to be batch order and batch size")
end
relation = relation.reorder(batch_order).limit(batch_size)
records = start ? relation.where(table['created_at'].gteq(start)).to_a : relation.to_a
while records.any?
records_size = records.size
created_at_offset = records.last.created_at
raise "Primary key not included in the custom select clause" unless created_at_offset
yield records
break if records_size < batch_size
records = relation.where(all.table['created_at'].gt(created_at_offset)).to_a
end
end
private
def batch_order
"#{quoted_table_name}.#{connection.quote_column_name('created_at')} ASC"
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment