# Validations based on negations of regular expressions.
# validates_not_format_of takes an array of attributes,
#  a regular expression to apply to them,
#  and an optional hash of configuration options.
# All other validations take an array of attributes,
#  a word or list of words to act upon,
#  and an optional hash of configuration options.
# Examples:
# validates_does_have_the_words :username, :description, %w(chicken yellow coward), :ignore_case => true
# In this case, the model will not be valid if the username or description attributes contain any of the
# restricted words, regardless of case.
module ActiveRecord
  module Validations
    module ClassMethods
      # Negates a regular expression match against an attribute.
      # Similar to grep -v
      def validates_not_format_of(*attr_names)
        configuration = { :message => ActiveRecord::Errors.default_error_messages[:invalid], :on => :save, :with => nil }
        configuration.update(attr_names.pop) if attr_names.last.is_a?(Hash)
        raise(ArgumentError, "A regular expression must be supplied as the :with option of the configuration hash") unless configuration[:with].is_a?(Regexp)
        validates_each(attr_names, configuration) do |record, attr_name, value|
          record.errors.add(attr_name, configuration[:message]) if value.to_s =~ configuration[:with]
      def validates_does_not_begin_with_the_word(*attr_names)
        validates_attributes_not_format_of_block(attr_names) { |word| "^#{word}" }
      alias :validates_does_not_begin_with_the_words :validates_does_not_begin_with_the_word
      # Validates an attribute does not end with the provided string, or strings.
      # Examples:
      # validates_does_not_end_with_the_word :username, '2000'
      #  or
      # validates_does_not_end_with_the_words :username, %w(xxx ooo 666 McFly)
      def validates_does_not_end_with_the_word(*attr_names)
        validates_attributes_not_format_of_block(attr_names) { |word| "#{word}$" }
      alias :validates_does_not_end_with_the_words :validates_does_not_end_with_the_word
      # Validates an attribute does not contain disallowed words
      # Examples:
      # validates_does_not_have_the_word :username, 'admin'
      #  or
      # validates_does_not_have_the_words :username, %w(admin guest moderator)
      def validates_does_not_have_the_word(*attr_names)
        validates_attributes_not_format_of_block(attr_names) { |word| word }
      alias :validates_does_not_have_the_words :validates_does_not_have_the_word
      def validates_is_not_the_word(*attr_names)
        validates_attributes_not_format_of_block(attr_names) { |word| "^#{word}$" }
      alias :validates_is_not_the_words :validates_is_not_the_word
      # The block supplied to validates_attributes_not_format_of_block must yield a string
      # that can be converted into a regular expression by Regexp.new
      # The argument supplied to the block is a string that has been regular-expression-quoted,
      # and is safe to use without further escaping.
      # You can pass options for how the regular expression is created in the final options hash.
      # Either use :ignore_case => true
      #  or
      # :regexp_options => Fixnum
      # either of which will be passed as the 2nd argument to Regexp.new, with :regexp_options taking precedence
      # See documentation on Regexp.new for more information on allowable values for :regexp_options
      def validates_attributes_not_format_of_block(attr_names, &block)
        options = attr_names.last.is_a?(Hash) ? attr_names.pop : { }
        word = attr_names.pop
        words = word.respond_to?(:each) ? word : [ word ]
        regexp_options = options.delete(:regexp_options) || options.delete(:ignore_case)
        restriction = Regexp.new(words.map { |w| "(#{yield Regexp.quote(w.to_s)})" }.join('|'), regexp_options)
        configuration = {
          # Overridable default configuration
          :message => 'is not valid',
          :on => :save
        }.merge(options || {}).merge(
          # Mandatory default configuration
          :with => restriction
        validates_not_format_of attr_names, configuration

def authorized_only &block
  @active_user ||= User.find_by_id( session[:user_id] )
  if @active_user
    yield block if block_given?
  elsif !block_given?
    flash[:notice] = "Please log in"
    redirect_to(:controller => "login", :action => "login")

module ActiveRecord
  class Base
    # Step through and instantiate each member of the class and execute on it,
    #   but instantiate no more than per_page instances at any given time.
    # Safe for destructive actions or actions that modify the fields
    # your :order or :conditions clauses operate on.
    def each_by_page per_page, options = {}, &block
      # By-id for model-modifying blocks
      # Build SQL to get ids of all matching records using the options provided by the user
      sql = construct_finder_sql(options.dup.merge({ :select => "`#{table_name}`.#{primary_key} AS id" }))
      # Get the results as an array of tiny hashes { "id" => "1" } and flatten them out to just the ids
      all_ids = connection.select_all(sql).map { |h| h['id'] }
      at_a_time = 0..(per_page-1)
      # chop apart the all_ids array a segment at a time
        ids = all_ids.slice!(at_a_time)
        ids_cases = []
        ids.each_with_index { |id, i| ids_cases << "WHEN #{id} THEN #{i}" }
        ids_cases = ids_cases.join(' ')
        # Do the deed on this page of results
        find(:all, options.merge(
          :conditions => [ "#{primary_key} IN (?)", ids ],
          :order => "CASE id #{ids_cases} END"
        )).each &block
      end until all_ids.empty?

This piece of code is perhaps named poorly. It arose from a need to operate on a large number of models during a migration.

Many migrations that operate on a large number of rows can accomplish their operation en-masse using an update_all.

User.update_all('filename = \'default.png\'', 'default_avatar = true')

However, sometimes the operation being performed is more complex. Perhaps its a destructive migration. Perhaps it operates on a complex graph of objects, or over a polymorphic association, or perhaps you’re relying on the propagation of ActiveRecord’s callbacks.

In any of these cases, you can easily exhaust available RAM with code such as this:

User.find(:all, :conditions => { :default_avatar => true } ) do |user| user.select_default_avatar end

ActiveRecord will first do a SQL SELECT with the provided parameters, instantiate each row of the result as an object in memory, and once all rows are instantiated, will iterate over the set, applying the block to each element.

Except if the number of rows returned is large enough, it never gets to the iterating part.

Instead of instantiating all the models at once, we instead instantiate them in bite-sized pieces.

User.each_by_page(:conditions => { :default_avatar => true } ) do |user| user.select_default_avatar end