Created
June 16, 2011 18:57
-
-
Save dkubb/1029959 to your computer and use it in GitHub Desktop.
DataMapper and Sunspot Integration Spike
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# gem install datamapper dm-sqlite-adapter sunspot sunspot_rails activesupport | |
require 'rubygems' | |
require 'datamapper' | |
require 'sunspot' | |
require 'sunspot/rails' | |
require 'active_support/all' | |
DataMapper::Logger.new($stdout, :debug) | |
DataMapper.setup(:default, 'sqlite::memory:') | |
module Sunspot | |
module DataMapper | |
def self.included(base) | |
base.class_eval do | |
alias new_record? new? | |
end | |
base.extend Sunspot::Rails::Searchable::ActsAsMethods | |
Sunspot::Adapters::DataAccessor.register(DataAccessor, base) | |
Sunspot::Adapters::InstanceAdapter.register(InstanceAdapter, base) | |
def base.before_save(*args, &block) | |
before(:save, *args, &block) | |
end | |
def base.after_save(*args, &block) | |
after(:save, *args, &block) | |
end | |
def base.after_destroy(*args, &block) | |
after(:destroy, *args, &block) | |
end | |
end | |
class InstanceAdapter < Sunspot::Adapters::InstanceAdapter | |
def id | |
@instance.id | |
end | |
end | |
class DataAccessor < Sunspot::Adapters::DataAccessor | |
def load(id) | |
@clazz.get(id) | |
end | |
def load_all(ids) | |
@clazz.all(:id => ids) | |
end | |
end | |
end | |
end | |
class User | |
include DataMapper::Resource | |
include Sunspot::DataMapper | |
property :id, Serial | |
property :name, String, :required => true, :unique => true | |
searchable do | |
string :name | |
end | |
end | |
DataMapper.auto_migrate! | |
User.create(:name => 'John Doe') | |
puts '-' * 80 | |
p User.all | |
p Sunspot.search(User).results |
Thanks for the helpful example code! In case this helps you or anyone else, I've rolled this gist into a higher-level gem here: https://github.com/brainix/data_mapped
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm sure there are ways to get this to work without requiring activesupport or sunspot_rails. I was mostly just copying some Mongoid and MongoMapper examples I found, trying to see if I could get things to the point where the last two statements would return the same results. If that was the case, it probably also wouldn't be necessary to have those
new_record?
or before/after hook aliases either.