ruby on rails - Confusion with super -


override to_xml.

what difference between these codes. can explain proper example ?

1.

def to_xml(options = {})   options.merge!(:methods  => [ :murm_case_name, :murm_type_name ])   super end 

2.

def to_xml(options = {})   super   options.merge!(:methods  => [ :murm_case_name, :murm_type_name ]) end 

tl;dr: super behaves in unexpected ways, , variables matter, not objects.

when super called, it's not called object passed in.

it's called variable called options @ time of call. example, following code:

class parent   def to_xml(options)     puts "#{self.class.inspect} options: #{options.inspect}"   end end  class originalchild < parent   def to_xml(options)     options.merge!(:methods  => [ :murm_case_name, :murm_type_name ])     super   end end  class secondchild < parent   def to_xml(options)     options = 42     super   end end  begin   parent_options, original_child_options, second_child_options = [{}, {}, {}]   parent.new.to_xml(parent_options)   puts "parent options after method called: #{parent_options.inspect}"   puts   originalchild.new.to_xml(original_child_options)   puts "original child options after method called: #{original_child_options.inspect}"   puts   second_child_options = {}   secondchild.new.to_xml(second_child_options)   puts "second child options after method called: #{second_child_options.inspect}"   puts end 

which produces output

parent options: {} parent options after method called: {}  originalchild options: {:methods=>[:murm_case_name, :murm_type_name]} original child options after method called: {:methods=>[:murm_case_name, :murm_type_name]}  secondchild options: 42 second child options after method called: {} 

you can see secondchild super method called variable options refers fixnum of value 42, not object referred options.

with using options.merge!, you'd modify hash object passed you, means object referred variable original_child_options modified, can seen in original child options after method called: {:methods=>[:murm_case_name, :murm_type_name]} line.

(note: changed options 42 in secondchild, rather call hash#merge, because wanted show wasn't merely case of side effects on object)


Comments

Popular posts from this blog

android - Spacing between the stars of a rating bar? -

html - Instapaper-like algorithm -

c# - How to execute a particular part of code asynchronously in a class -