1
0
Fork 0
mirror of https://github.com/aasm/aasm synced 2023-03-27 23:22:41 -04:00

Merge pull request #290 from jethroo/chore/refactoring_base_to_reduce_complexity

refactoring Base#state_with_scope to reduce complexity of the method
This commit is contained in:
Thorsten Böttger 2015-12-08 23:55:06 +13:00
commit ea0b5a8a23

View file

@ -55,35 +55,62 @@ module AASM
# 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)
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
end
create_scope(name) if create_scope?(name)
end
alias_method :state_without_scope, :state
alias_method :state, :state_with_scope
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
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