begin
  require 'activerecord'
rescue LoadError
  require 'active_record'
end

class ActiveRecord::Base
  module PickleAdapter
    include Pickle::Adapter::Base

    # Do not consider these to be part of the class list
    def self.except_classes
      @@except_classes ||= [
        "CGI::Session::ActiveRecordStore::Session",
        "ActiveRecord::SessionStore::Session"
      ]
    end

    # Gets a list of the available models for this adapter
    def self.model_classes
      if ::ActiveRecord::Base.respond_to?(:descendants)
        klasses = ::ActiveRecord::Base.descendants  # Rails 3, 4
      else
        klasses = ::ActiveRecord::Base.subclasses   # Rails 2
      end

      klasses.select do |klass|
        !klass.abstract_class? && klass.table_exists? && !except_classes.include?(klass.name)
      end
    end

    # get a list of column names for a given class
    def self.column_names(klass)
      klass.column_names
    end

    # Get an instance by id of the model
    def self.get_model(klass, id)
      klass.find(id)
    end

    # Find the first instance matching conditions
    def self.find_first_model(klass, conditions)
      if defined? ::ActiveRecord::Relation
        klass.where(conditions).first           # Rails 3, 4
      else
        klass.find(:first,
                   :conditions => conditions)   # Rails 2
      end
    end

    # Find all models matching conditions
    def self.find_all_models(klass, conditions)
      if defined? ::ActiveRecord::Relation
        klass.where(conditions)                 # Rails 3, 4
      else
        klass.find(:all,
                   :conditions => conditions)   # Rails 2
      end
    end

    # Create a model using attributes
    def self.create_model(klass, attributes)
      klass.create!(attributes)
    end
  end
end
