lib/larynx/fields.rb in larynx-0.1.4 vs lib/larynx/fields.rb in larynx-0.1.5
- old
+ new
@@ -24,34 +24,51 @@
module InstanceMethods
def initialize(*args, &block)
@fields = self.class.field_definitions.map {|field| Field.new(field[:name], field[:options], &field[:block]) }
- @current_field = 0
+ @field_index = -1
super
end
def next_field(field_name=nil)
- @current_field = field_index(field_name) if field_name
- if field = @fields[@current_field]
+ if field_name
+ @field_index = field_index(field_name)
+ else
+ @field_index += 1
+ end
+ if field = current_field
field.run(self)
- @current_field += 1
field
end
end
+ def current_field
+ @fields[@field_index]
+ end
+
def field_index(name)
field = @fields.find {|f| f.name == name }
@fields.index(field)
end
+ def attempt
+ current_field.attempt
+ end
+
+ def last_attempt?
+ current_field.last_attempt?
+ end
+
end
class Field
include CallbacksWithAsync
- attr_reader :name, :app
+ VALID_PROMPT_OPTIONS = [:play, :speak, :phrase, :bargein, :repeats, :interdigit_timeout, :timeout]
+
+ attr_reader :name, :app, :attempt
define_callback :setup, :validate, :invalid, :success, :failure, :scope => :app
def initialize(name, options, &block)
@name = name
@options = options.reverse_merge(:attempts => 3)
@@ -69,11 +86,11 @@
raise 'A reprompt can only be used after a prompt' if @prompt_queue.empty?
add_prompt(options)
end
def add_prompt(options)
- options.assert_valid_keys(:play, :speak, :phrase, :bargein, :repeats, :interdigit_timeout, :timeout)
+ options.assert_valid_keys(*VALID_PROMPT_OPTIONS)
repeats = options.delete(:repeats) || 1
options.merge!(@options.slice(:length, :min_length, :max_length, :interdigit_timeout, :timeout))
@prompt_queue += ([options] * repeats)
end
@@ -97,14 +114,13 @@
def increment_attempts
@attempt += 1
end
# hook called when callback is complete
- def callback_complete(callback, result)
+ def callback_complete(callback, result=true)
case callback
when :validate
- result = result.nil? ? true : result
evaluate_validity(result)
when :invalid
invalid_input
when :success, :failure
finalize
@@ -118,15 +134,15 @@
def evaluate_validity(result)
result ? fire_callback(:success) : fire_callback(:invalid)
end
def invalid_input
- if @attempt < @options[:attempts]
+ if last_attempt?
+ fire_callback(:failure)
+ else
increment_attempts
execute_prompt
- else
- fire_callback(:failure)
end
end
def send_next_command
call.send_next_command if call.state == :ready
@@ -136,11 +152,11 @@
@value, @valid_length = input, result
@app.send("#{@name}=", input)
end
def command_from_options(options)
- ([:play, :speak, :phrase] & options.keys).first
+ (Prompt::COMMAND_OPTIONS & options.keys).first
end
def run(app)
@app = app
@attempt = 1
@@ -154,9 +170,13 @@
end
def finalize
call.remove_observer self
send_next_command
+ end
+
+ def last_attempt?
+ @attempt == @options[:attempts]
end
end
end