module Ix
	module HasIx
	
		extend ActiveSupport::Concern
		
		included do
			before_save :set_ix
		end
		
		module ClassMethods
		
			def has_ix(options = {})
				cattr_accessor :ix_length
				self.ix_length = (options[:length] / 2) || 4
			
				include Ix::HasIx::LocalInstanceMethods
			end
			
			def find_ix(ix)
				self.find_by ix: ix
			end
			
			def fill_blank_ixs
				self.where(ix: nil).each do |record|
					record.save
				end
			end
			
		end
		
		
		module LocalInstanceMethods
		
			def ix?
				self.has_attribute? :ix
			end
		
			private
			
				def set_ix
					if self.ix? && self.ix.blank?
						begin
							self.ix = SecureRandom.hex(self.ix_length) 
						end while self.class.exists?(ix: self.ix)
					end
				end

		end
		
	end
end

ActiveRecord::Base.send :include, Ix::HasIx