Sha256: 53c26819fd205467d6516072cb5c789125fcdf030f2bb5a6bcc68af5e6254dd0

Contents?: true

Size: 1.66 KB

Versions: 2

Compression:

Stored size: 1.66 KB

Contents

module HasUuid
  VALID_FORMAT = /^([0-9a-f]{8})-([0-9a-f]{4})-([0-9a-f]{4})-([0-9a-f]{2})([0-9a-f]{2})-([0-9a-f]{12})$/

  module ActiveRecord
    module FinderMethods
      def find_one(id)
        if id.is_a?(::UUIDTools::UUID) || id.to_s =~ VALID_FORMAT
          id = ::UUIDTools::UUID.parse(id) if id.is_a?(String)
          return self.find_by_uuid!(id)
        end
        super
      end

      def find_some(ids)
        if ids.length > 0 && ids.inject(true) { |r, id| r && (id.is_a?(::UUIDTools::UUID) || id.to_s =~ VALID_FORMAT) }
          uuids = ids.map do |id|
            id = ::UUIDTools::UUID.parse(id) if id.is_a?(String)
            id
          end

          arr = where(table[:uuid].in(uuids))
          if ::ActiveRecord::VERSION::MAJOR >= 4
            result = arr.load
          else
            result = arr.all
          end

          expected_size =
            if @limit_value && ids.size > @limit_value
              @limit_value
            else
              ids.size
            end

            if @offset_value && (ids.size - @offset_value < expected_size)
              expected_size = ids.size - @offset_value
            end

            if result.size == expected_size
              result
            else
              conditions = arel.where_sql
              conditions = " [#{conditions}]" if conditions
              error = "Couldn't find all #{@klass.name.pluralize} with UUIDs "
              error << "(#{ids.join(", ")})#{conditions} (found #{result.size} results, but was looking for #{expected_size})"
              raise ::ActiveRecord::RecordNotFound, error
            end
        else
          super
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rails_has_uuid-0.3.0 lib/has_uuid/active_record/finder_methods.rb
rails_has_uuid-0.2.0 lib/has_uuid/active_record/finder_methods.rb