Sha256: c0d9f74e4400f7bbb1e43f888bf4cb83204cae1f74b3c4db9b9e80b2a5ac3370

Contents?: true

Size: 1.65 KB

Versions: 2

Compression:

Stored size: 1.65 KB

Contents

require 'mongoid'

module Mongoid
  module Document
    module ClassMethods
      include OrmAdapter::ToAdapter
    end
    
    class OrmAdapter < ::OrmAdapter::Base
      # Do not consider these to be part of the class list
      def self.except_classes
        @@except_classes ||= []
      end

      # Gets a list of the available models for this adapter
      def self.model_classes
        ObjectSpace.each_object(Class).to_a.select {|klass| klass.ancestors.include? Mongoid::Document}
      end

      # get a list of column names for a given class
      def column_names
        klass.fields.keys
      end

      # Get an instance by id of the model
      def get!(id)
        klass.find(wrap_key(id))
      end

      # Get an instance by id of the model
      def get(id)
        klass.first(:conditions => { :id => wrap_key(id) })
      end

      # Find the first instance matching conditions
      def find_first(conditions)
        klass.first(:conditions => conditions_to_fields(conditions))
      end

      # Find all models matching conditions
      def find_all(conditions)
        klass.all(:conditions => conditions_to_fields(conditions))
      end

      # Create a model with given attributes
      def create!(attributes)
        klass.create!(attributes)
      end
  
    protected

      # converts and documents to ids
      def conditions_to_fields(conditions)
        conditions.inject({}) do |fields, (key, value)|
          if value.is_a?(Mongoid::Document) && klass.fields.keys.include?("#{key}_id")
            fields.merge("#{key}_id" => value.id)
          else
            fields.merge(key => value)
          end
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
orm_adapter-0.0.3 lib/orm_adapter/adapters/mongoid.rb
orm_adapter-0.0.2 lib/orm_adapter/adapters/mongoid.rb