Merge pull request #203 from reidmorrison/master

Add support for MongoMapper
This commit is contained in:
Thorsten Böttger 2015-02-22 11:24:54 +13:00
commit d43c6a98a0
17 changed files with 425 additions and 10 deletions

View File

@ -10,7 +10,7 @@ rvm:
- 2.1
- 2.2
# - jruby-18mode # JRuby in 1.8 mode
- jruby-19mode # JRuby in 1.9 mode
- jruby-1.7 # JRuby in 1.9 mode
- rbx-2.2.1
services: mongodb
@ -18,13 +18,16 @@ services: mongodb
gemfile:
- gemfiles/rails_3.2.gemfile
- gemfiles/rails_4.0.gemfile
- gemfiles/rails_4.0_bson1.gemfile
- gemfiles/rails_4.1.gemfile
- gemfiles/rails_4.1_bson1.gemfile
- gemfiles/rails_4.2.gemfile
- gemfiles/rails_4.2_bson1.gemfile
matrix:
allow_failures:
- rvm: rbx-2.2.1
- rvm: jruby-19mode
- rvm: jruby-1.7
exclude:
- rvm: 1.9.3
gemfile: gemfiles/rails_4.1.gemfile

View File

@ -6,7 +6,11 @@ gem 'rubysl', :platforms => :rbx
gem "jruby-openssl", :platforms => :jruby
gem "activerecord-jdbcsqlite3-adapter", :platforms => :jruby
gem "rails", "~>4.1"
gem 'mongoid'
gem 'mongoid', '~>4.0' if Gem::Version.create(RUBY_VERSION.dup) >= Gem::Version.create('1.9.3')
gem 'sequel'
# Since mongoid V4 requires incompatible bson V2, cannot have mongoid (V4 or greater)
# and mongo_mapper ( or mongo ) in the same application
#gem 'mongo_mapper', '~> 0.13'
#gem 'bson_ext', :platforms => :ruby
gemspec

View File

@ -9,8 +9,8 @@ This package contains AASM, a library for adding finite state machines to Ruby c
AASM started as the *acts_as_state_machine* plugin but has evolved into a more generic library
that no longer targets only ActiveRecord models. It currently provides adapters for
[ActiveRecord](http://api.rubyonrails.org/classes/ActiveRecord/Base.html) and
[Mongoid](http://mongoid.org/), but it can be used for any Ruby class, no matter what
[ActiveRecord](http://api.rubyonrails.org/classes/ActiveRecord/Base.html),
[Mongoid](http://mongoid.org/), and [Mongomapper](http://mongomapper.com/) but it can be used for any Ruby class, no matter what
parent class it has (if any).
## Upgrade from version 3 to 4
@ -435,7 +435,7 @@ to ```false```.
### Sequel
AASM also supports [Sequel](http://sequel.jeremyevans.net/) besides _ActiveRecord_ and _Mongoid_.
AASM also supports [Sequel](http://sequel.jeremyevans.net/) besides _ActiveRecord_, _Mongoid_, and _MongoMapper_.
```ruby
class Job < Sequel::Model
@ -466,6 +466,23 @@ class Job
end
```
### MongoMapper
AASM also supports persistence to Mongodb if you're using MongoMapper. Make sure
to include MongoMapper::Document before you include AASM.
```ruby
class Job
include MongoMapper::Document
include AASM
key :aasm_state, Symbol
aasm do
...
end
end
```
### Automatic Scopes
AASM will automatically create scope methods for each state in the model.

View File

@ -7,7 +7,9 @@ gem 'rubinius-developer_tools', :platforms => :rbx
gem "jruby-openssl", :platforms => :jruby
gem "activerecord-jdbcsqlite3-adapter", :platforms => :jruby
gem "rails", "3.2.21"
gem 'mongoid' if Gem::Version.create(RUBY_VERSION.dup) >= Gem::Version.create('1.9.3')
gem 'mongoid', '~>3.1' if Gem::Version.create(RUBY_VERSION.dup) >= Gem::Version.create('1.9.3')
gem 'sequel'
gem 'mongo_mapper', '~>0.13'
gem 'bson_ext', :platforms => :ruby
gemspec :path => "../"

View File

@ -7,7 +7,7 @@ gem 'rubinius-developer_tools', :platforms => :rbx
gem "jruby-openssl", :platforms => :jruby
gem "activerecord-jdbcsqlite3-adapter", :platforms => :jruby
gem "rails", "4.0.13"
gem 'mongoid' if Gem::Version.create(RUBY_VERSION.dup) >= Gem::Version.create('1.9.3')
gem 'mongoid', '~>4.0' if Gem::Version.create(RUBY_VERSION.dup) >= Gem::Version.create('1.9.3')
gem 'sequel'
gemspec :path => "../"

View File

@ -0,0 +1,14 @@
source "https://rubygems.org"
gem "sqlite3", :platforms => :ruby
gem "coveralls"
gem 'rubysl', :platforms => :rbx
gem 'rubinius-developer_tools', :platforms => :rbx
gem "jruby-openssl", :platforms => :jruby
gem "activerecord-jdbcsqlite3-adapter", :platforms => :jruby
gem "rails", "4.0.13"
gem 'sequel'
gem 'mongo_mapper', '~>0.13'
gem 'bson_ext', :platforms => :ruby
gemspec :path => "../"

View File

@ -7,7 +7,7 @@ gem 'rubinius-developer_tools', :platforms => :rbx
gem "jruby-openssl", :platforms => :jruby
gem "activerecord-jdbcsqlite3-adapter", :platforms => :jruby
gem "rails", "4.1.9"
gem 'mongoid' if Gem::Version.create(RUBY_VERSION.dup) >= Gem::Version.create('1.9.3')
gem 'mongoid', '~>4.0' if Gem::Version.create(RUBY_VERSION.dup) >= Gem::Version.create('1.9.3')
gem 'sequel'
gemspec :path => "../"

View File

@ -0,0 +1,14 @@
source "https://rubygems.org"
gem "sqlite3", :platforms => :ruby
gem "coveralls"
gem 'rubysl', :platforms => :rbx
gem 'rubinius-developer_tools', :platforms => :rbx
gem "jruby-openssl", :platforms => :jruby
gem "activerecord-jdbcsqlite3-adapter", :platforms => :jruby
gem "rails", "4.1.9"
gem 'sequel'
gem 'mongo_mapper', '~> 0.13'
gem 'bson_ext', :platforms => :ruby
gemspec :path => "../"

View File

@ -7,7 +7,7 @@ gem 'rubinius-developer_tools', :platforms => :rbx
gem "jruby-openssl", :platforms => :jruby
gem "activerecord-jdbcsqlite3-adapter", :platforms => :jruby
gem "rails", "4.2.0"
gem 'mongoid' if Gem::Version.create(RUBY_VERSION.dup) >= Gem::Version.create('1.9.3')
gem 'mongoid', '~>4.0' if Gem::Version.create(RUBY_VERSION.dup) >= Gem::Version.create('1.9.3')
gem 'sequel'
gemspec :path => "../"

View File

@ -0,0 +1,14 @@
source "https://rubygems.org"
gem "sqlite3", :platforms => :ruby
gem "coveralls"
gem 'rubysl', :platforms => :rbx
gem 'rubinius-developer_tools', :platforms => :rbx
gem "jruby-openssl", :platforms => :jruby
gem "activerecord-jdbcsqlite3-adapter", :platforms => :jruby
gem "rails", "4.2.0"
gem 'sequel'
gem 'mongo_mapper'
gem 'bson_ext', :platforms => :ruby
gemspec :path => "../"

View File

@ -10,6 +10,8 @@ module AASM
include_persistence base, :active_record
elsif hierarchy.include?("Mongoid::Document")
include_persistence base, :mongoid
elsif hierarchy.include?("MongoMapper::Document")
include_persistence base, :mongo_mapper
elsif hierarchy.include?("Sequel::Model")
include_persistence base, :sequel
else

View File

@ -71,6 +71,9 @@ module AASM
elsif @klass.ancestors.map {|klass| klass.to_s}.include?("Mongoid::Document")
scope_options = lambda { @klass.send(:where, {@klass.aasm.attribute_name.to_sym => name.to_s}) }
@klass.send(:scope, name, scope_options)
elsif @klass.ancestors.map {|klass| klass.to_s}.include?("MongoMapper::Document")
conditions = { @klass.aasm.attribute_name.to_sym => name.to_s }
@klass.scope(name, lambda { @klass.where(conditions) })
end
end
end

View File

@ -0,0 +1,174 @@
require_relative 'base'
module AASM
module Persistence
module MongoMapperPersistence
# This method:
#
# * extends the model with ClassMethods
# * includes InstanceMethods
#
# Adds
#
# before_validation :aasm_ensure_initial_state, :on => :create
#
# As a result, it doesn't matter when you define your methods - the following 2 are equivalent
#
# class Foo
# include MongoMapper::Document
# def aasm_write_state(state)
# "bar"
# end
# include AASM
# end
#
# class Foo < ActiveRecord::Base
# include MongoMapper::Document
# include AASM
# def aasm_write_state(state)
# "bar"
# end
# end
#
def self.included(base)
base.send(:include, AASM::Persistence::Base)
base.extend AASM::Persistence::MongoMapperPersistence::ClassMethods
base.send(:include, AASM::Persistence::MongoMapperPersistence::InstanceMethods)
base.before_create :aasm_ensure_initial_state
# ensure state is in the list of states
base.validate :aasm_validate_states
end
module ClassMethods
def find_in_state(number, state, *args)
with_state_scope(state).find!(number, *args)
end
def count_in_state(state, *args)
with_state_scope(state).count(*args)
end
def calculate_in_state(state, *args)
with_state_scope(state).calculate(*args)
end
protected
def with_state_scope(state)
where(aasm.attribute_name.to_sym => state.to_s)
end
end
module InstanceMethods
# Writes <tt>state</tt> to the state column and persists it to the database
#
# foo = Foo.find(1)
# foo.aasm.current_state # => :opened
# foo.close!
# foo.aasm.current_state # => :closed
# Foo.find(1).aasm.current_state # => :closed
#
# NOTE: intended to be called from an event
def aasm_write_state(state)
old_value = read_attribute(self.class.aasm.attribute_name)
aasm_write_attribute state
success = if aasm_skipping_validations
value = aasm_raw_attribute_value state
self.class.where(self.class.primary_key => self.id).update_all(self.class.aasm.attribute_name => value) == 1
else
self.save
end
unless success
write_attribute(self.class.aasm.attribute_name, old_value)
return false
end
true
end
# Writes <tt>state</tt> to the state column, but does not persist it to the database
#
# foo = Foo.find(1)
# foo.aasm.current_state # => :opened
# foo.close
# foo.aasm.current_state # => :closed
# Foo.find(1).aasm.current_state # => :opened
# foo.save
# foo.aasm.current_state # => :closed
# Foo.find(1).aasm.current_state # => :closed
#
# NOTE: intended to be called from an event
def aasm_write_state_without_persistence(state)
aasm_write_attribute state
end
private
def aasm_enum
case AASM::StateMachine[self.class].config.enum
when false then nil
when true then aasm_guess_enum_method
when nil then aasm_guess_enum_method if aasm_column_looks_like_enum
else AASM::StateMachine[self.class].config.enum
end
end
def aasm_column_looks_like_enum
self.class.keys[self.class.aasm.attribute_name.to_s].type == Integer
end
def aasm_guess_enum_method
self.class.aasm.attribute_name.to_s.pluralize.to_sym
end
def aasm_skipping_validations
AASM::StateMachine[self.class].config.skip_validation_on_save
end
def aasm_write_attribute(state)
write_attribute self.class.aasm.attribute_name, aasm_raw_attribute_value(state)
end
def aasm_raw_attribute_value(state)
if aasm_enum
self.class.send(aasm_enum)[state]
else
state.to_s
end
end
# Ensures that if the aasm_state column is nil and the record is new
# that the initial state gets populated before validation on create
#
# foo = Foo.new
# foo.aasm_state # => nil
# foo.valid?
# foo.aasm_state # => "open" (where :open is the initial state)
#
#
# foo = Foo.find(:first)
# foo.aasm_state # => 1
# foo.aasm_state = nil
# foo.valid?
# foo.aasm_state # => nil
#
def aasm_ensure_initial_state
return send("#{self.class.aasm.attribute_name}=", aasm.enter_initial_state.to_s) if send(self.class.aasm.attribute_name).blank?
end
def aasm_validate_states
send("#{self.class.aasm.attribute_name}=", aasm.enter_initial_state.to_s) if send(self.class.aasm.attribute_name).blank?
unless AASM::StateMachine[self.class].config.skip_validation_on_save
if aasm.current_state && !aasm.states.include?(aasm.current_state)
self.errors.add(AASM::StateMachine[self.class].config.column , "is invalid")
end
end
end
end # InstanceMethods
end
end # Persistence
end # AASM

View File

@ -0,0 +1,10 @@
class NoScopeMongoMapper
include MongoMapper::Document
include AASM
key :status, String
aasm :create_scopes => false, :column => :status do
state :ignored_scope
end
end

View File

@ -0,0 +1,11 @@
class SimpleMongoMapper
include MongoMapper::Document
include AASM
key :status, String
aasm column: :status do
state :unknown_scope
state :next
end
end

View File

@ -0,0 +1,12 @@
class SimpleNewDslMongoMapper
include MongoMapper::Document
include AASM
key :status, String
aasm :column => :status
aasm do
state :unknown_scope
state :next
end
end

View File

@ -0,0 +1,135 @@
describe 'mongo_mapper' do
begin
require 'mongo_mapper'
require 'logger'
require 'spec_helper'
before(:all) do
Dir[File.dirname(__FILE__) + "/../../models/mongo_mapper/*.rb"].sort.each { |f| require File.expand_path(f) }
config = {
'test' => {
'database' => "mongo_mapper_#{Process.pid}"
}
}
MongoMapper.setup(config, 'test') #, :logger => Logger.new(STDERR))
end
after do
# Clear Out all non-system Mongo collections between tests
MongoMapper.database.collections.each do |collection|
collection.drop unless collection.capped? || (collection.name =~ /\Asystem/)
end
end
describe "named scopes with the old DSL" do
context "Does not already respond_to? the scope name" do
it "should add a scope" do
expect(SimpleMongoMapper).to respond_to(:unknown_scope)
expect(SimpleMongoMapper.unknown_scope.class).to eq(MongoMapper::Plugins::Querying::DecoratedPluckyQuery)
#expect(SimpleMongoMapper.unknown_scope.is_a?(ActiveRecord::Relation)).to be_truthy
end
end
context "Already respond_to? the scope name" do
it "should not add a scope" do
expect(SimpleMongoMapper).to respond_to(:next)
expect(SimpleMongoMapper.new.class).to eq(SimpleMongoMapper)
end
end
end
describe "named scopes with the new DSL" do
context "Does not already respond_to? the scope name" do
it "should add a scope" do
expect(SimpleNewDslMongoMapper).to respond_to(:unknown_scope)
expect(SimpleNewDslMongoMapper.unknown_scope.class).to eq(MongoMapper::Plugins::Querying::DecoratedPluckyQuery)
end
end
context "Already respond_to? the scope name" do
it "should not add a scope" do
expect(SimpleNewDslMongoMapper).to respond_to(:next)
expect(SimpleNewDslMongoMapper.new.class).to eq(SimpleNewDslMongoMapper)
end
end
it "does not create scopes if requested" do
expect(NoScopeMongoMapper).not_to respond_to(:ignored_scope)
end
end
describe "#find_in_state" do
let!(:model) { SimpleNewDslMongoMapper.create!(:status => :unknown_scope) }
let!(:model_id) { model._id }
it "should respond to method" do
expect(SimpleNewDslMongoMapper).to respond_to(:find_in_state)
end
it "should find the model when given the correct scope and model id" do
expect(SimpleNewDslMongoMapper.find_in_state(model_id, 'unknown_scope').class).to eq(SimpleNewDslMongoMapper)
expect(SimpleNewDslMongoMapper.find_in_state(model_id, 'unknown_scope')).to eq(model)
end
it "should raise DocumentNotFound error when given incorrect scope" do
expect {SimpleNewDslMongoMapper.find_in_state(model_id, 'next')}.to raise_error MongoMapper::DocumentNotFound
end
it "should raise DocumentNotFound error when given incorrect model id" do
expect {SimpleNewDslMongoMapper.find_in_state('bad_id', 'unknown_scope')}.to raise_error MongoMapper::DocumentNotFound
end
end
describe "#count_in_state" do
before do
3.times { SimpleNewDslMongoMapper.create!(:status => :unknown_scope) }
end
it "should respond to method" do
expect(SimpleNewDslMongoMapper).to respond_to(:count_in_state)
end
it "should return n for a scope with n records persisted" do
expect(SimpleNewDslMongoMapper.count_in_state('unknown_scope').class).to eq(Fixnum)
expect(SimpleNewDslMongoMapper.count_in_state('unknown_scope')).to eq(3)
end
it "should return zero for a scope without records persisted" do
expect(SimpleNewDslMongoMapper.count_in_state('next').class).to eq(Fixnum)
expect(SimpleNewDslMongoMapper.count_in_state('next')).to eq(0)
end
end
describe "instance methods" do
let(:simple) {SimpleNewDslMongoMapper.new}
it "should call aasm_ensure_initial_state on validation before create" do
expect(SimpleNewDslMongoMapper.aasm.initial_state).to eq(:unknown_scope)
expect(SimpleNewDslMongoMapper.aasm.attribute_name).to eq(:status)
expect(simple.status).to eq(nil)
simple.valid?
expect(simple.status).to eq('unknown_scope')
end
it "should call aasm_ensure_initial_state before create, even if skipping validations" do
expect(simple.status).to eq(nil)
simple.save(:validate => false)
expect(simple.status).to eq('unknown_scope')
end
end
rescue LoadError
puts "Not running MongoMapper specs because mongo_mapper gem is not installed!!!"
end
end