lib/bindata/choice.rb in bindata-1.5.1 vs lib/bindata/choice.rb in bindata-1.6.0
- old
+ new
@@ -105,31 +105,28 @@
end
end
end
def initialize_shared_instance
- if eval_parameter(:copy_on_change) == true
- class << self
- alias_method :hook_after_current_choice, :copy_previous_value
- end
- end
+ extend CopyOnChangePlugin if eval_parameter(:copy_on_change) == true
+ super
end
def initialize_instance
@choices = {}
@last_selection = nil
end
- # A convenience method that returns the current selection.
+ # Returns the current selection.
def selection
- eval_parameter(:selection)
+ selection = eval_parameter(:selection)
+ if selection.nil?
+ raise IndexError, ":selection returned nil for #{debug_name}"
+ end
+ selection
end
- def clear #:nodoc:
- initialize_instance
- end
-
def clear? #:nodoc:
current_choice.clear?
end
def assign(val)
@@ -143,19 +140,18 @@
def respond_to?(symbol, include_private = false) #:nodoc:
current_choice.respond_to?(symbol, include_private) || super
end
def safe_respond_to?(symbol, include_private = false) #:nodoc:
- orig_respond_to?(symbol, include_private)
+ base_respond_to?(symbol, include_private)
end
def method_missing(symbol, *args, &block) #:nodoc:
current_choice.__send__(symbol, *args, &block)
end
def do_read(io) #:nodoc:
- hook_before_do_read
current_choice.do_read(io)
end
def do_write(io) #:nodoc:
current_choice.do_write(io)
@@ -166,40 +162,36 @@
end
#---------------
private
- def hook_before_do_read; end
- def hook_after_current_choice(*args); end
-
def current_choice
- selection = eval_parameter(:selection)
- if selection.nil?
- raise IndexError, ":selection returned nil for #{debug_name}"
- end
-
- obj = get_or_instantiate_choice(selection)
- hook_after_current_choice(selection, obj)
-
- obj
+ current_selection = selection
+ @choices[current_selection] ||= instantiate_choice(current_selection)
end
- def get_or_instantiate_choice(selection)
- @choices[selection] ||= instantiate_choice(selection)
- end
-
def instantiate_choice(selection)
prototype = get_parameter(:choices)[selection]
if prototype.nil?
raise IndexError, "selection '#{selection}' does not exist in :choices for #{debug_name}"
end
prototype.instantiate(nil, self)
end
+ end
- def copy_previous_value(selection, obj)
- prev = get_previous_choice(selection)
+ # Logic for the :copy_on_change parameter
+ module CopyOnChangePlugin
+ def current_choice
+ obj = super
+ copy_previous_value(obj)
+ obj
+ end
+
+ def copy_previous_value(obj)
+ current_selection = selection
+ prev = get_previous_choice(current_selection)
obj.assign(prev) unless prev.nil?
- remember_current_selection(selection)
+ remember_current_selection(current_selection)
end
def get_previous_choice(selection)
if selection != @last_selection and @last_selection != nil
@choices[@last_selection]