Permalink
Browse files

git-svn-id: http://elitists.textdriven.com/svn/plugins/acts_as_state_…

…machine/trunk@65 a9f67fa3-8408-0410-ad84-b6cefbfd10ac
  • Loading branch information...
1 parent 334d29e commit 64de098b3ef9e865bfa43c52040c9f7677d0886d sbarron committed Jul 23, 2006
Showing with 26 additions and 19 deletions.
  1. +24 −17 lib/acts_as_state_machine.rb
  2. +2 −2 test/schema.rb
@@ -223,37 +223,44 @@ def state(name, opts={})
# Wraps ActiveRecord::Base.find to conveniently find all records in
# a given state. Options:
#
- # * +number+ - This is just :first or :all from ActiveRecord
+ # * +number+ - This is just :first or :all from ActiveRecord +find+
# * +state+ - The state to find
# * +args+ - The rest of the args are passed down to ActiveRecord +find+
def find_in_state(number, state, *args)
- raise InvalidState unless states.include?(state)
-
- options = args.last.is_a?(Hash) ? args.pop : {}
- if options[:conditions]
- options[:conditions].first << " AND #{self.state_column} = ?"
- options[:conditions] << state.to_s
- else
- options[:conditions] = ["#{self.state_column} = ?", state.to_s]
+ with_state_scope state do
+ find(number, *args)
end
- self.find(number, options)
end
# Wraps ActiveRecord::Base.count to conveniently count all records in
# a given state. Options:
#
# * +state+ - The state to find
# * +args+ - The rest of the args are passed down to ActiveRecord +find+
- def count_in_state(state, conditions=nil)
+ def count_in_state(state, *args)
+ with_state_scope state do
+ count(*args)
+ end
+ end
+
+ # Wraps ActiveRecord::Base.calculate to conveniently calculate all records in
+ # a given state. Options:
+ #
+ # * +state+ - The state to find
+ # * +args+ - The rest of the args are passed down to ActiveRecord +calculate+
+ def calculate_in_state(state, *args)
+ with_state_scope state do
+ calculate(*args)
+ end
+ end
+
+ protected
+ def with_state_scope(state)
raise InvalidState unless states.include?(state)
- if conditions
- conditions.first << " AND #{self.state_column} = ?"
- conditions << state.to_s
- else
- conditions = ["#{self.state_column} = ?", state.to_s]
+ with_scope :find => {:conditions => ["#{table_name}.#{state_column} = ?", state.to_s]} do
+ yield if block_given?
end
- self.count(conditions)
end
end
end
View
@@ -1,11 +1,11 @@
ActiveRecord::Schema.define(:version => 1) do
- create_table :conversations do |t|
+ create_table :conversations, :force => true do |t|
t.column :state_machine, :string
t.column :subject, :string
t.column :closed, :boolean
end
- create_table :people do |t|
+ create_table :people, :force => true do |t|
t.column :name, :string
end
end

0 comments on commit 64de098

Please sign in to comment.