Skip to content

Commit

Permalink
refactoring Base#state_with_scope to reduce complexity of the method
Browse files Browse the repository at this point in the history
  • Loading branch information
Carsten Wirth committed Dec 6, 2015
1 parent f5c9bfe commit a04f505
Showing 1 changed file with 52 additions and 25 deletions.
77 changes: 52 additions & 25 deletions lib/aasm/persistence/base.rb
Expand Up @@ -55,35 +55,62 @@ class Base
# make sure to create a (named) scope for each state
def state_with_scope(name, *args)
state_without_scope(name, *args)
if @state_machine.config.create_scopes && !@klass.respond_to?(name)
create_scope(name) if create_scope?(name)
end
alias_method :state_without_scope, :state
alias_method :state, :state_with_scope

if @klass.ancestors.map {|klass| klass.to_s}.include?("ActiveRecord::Base")
conditions = {"#{@klass.table_name}.#{@klass.aasm(@name).attribute_name}" => name.to_s}
if ActiveRecord::VERSION::MAJOR >= 3
@klass.class_eval do
scope name, lambda { where(conditions) }
end
else
@klass.class_eval do
named_scope name, :conditions => conditions
end
end
elsif @klass.ancestors.map {|klass| klass.to_s}.include?("Mongoid::Document")
klass = @klass
state_machine_name = @name
scope_options = lambda {
klass.send(:where, {klass.aasm(state_machine_name).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(@name).attribute_name.to_sym => name.to_s }
@klass.scope(name, lambda { @klass.where(conditions) })
end
private

def create_scope?(name)
@state_machine.config.create_scopes && !@klass.respond_to?(name)
end

def create_scope(name)
if ancestors_include?("ActiveRecord::Base")
create_for_active_record(name)
elsif ancestors_include?("Mongoid::Document")
create_for_mongoid(name)
elsif ancestors_include?("MongoMapper::Document")
create_for_mongomapper(name)
end
end
alias_method :state_without_scope, :state
alias_method :state, :state_with_scope

def ancestors_include?(class_name)
@klass.ancestors.map { |klass| klass.to_s }.include?(class_name)
end

def create_for_active_record(name)
conditions = {
"#{@klass.table_name}.#{@klass.aasm(@name).attribute_name}" => name.to_s
}
if ActiveRecord::VERSION::MAJOR >= 3
@klass.class_eval do
scope name, lambda { where(conditions) }
end
else
@klass.class_eval do
named_scope name, :conditions => conditions
end
end
end

def create_for_mongoid(name)
klass = @klass
state_machine_name = @name
scope_options = lambda {
klass.send(
:where,
{ klass.aasm(state_machine_name).attribute_name.to_sym => name.to_s }
)
}
@klass.send(:scope, name, scope_options)
end

def create_for_mongomapper(name)
conditions = { @klass.aasm(@name).attribute_name.to_sym => name.to_s }
@klass.scope(name, lambda { @klass.where(conditions) })
end
end # Base

end # AASM

0 comments on commit a04f505

Please sign in to comment.