Advertisement
Guest User

Untitled

a guest
Mar 10th, 2019
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Rails 0.91 KB | None | 0 0
  1.   def method_missing(method_name, *args, &block)
  2.     if method_name =~ /^swap_(.+)_with(!?)$/
  3.       property = $1
  4.       is_bang  = $2 == '!'
  5.       sibling  = args[0]
  6.       #errors
  7.       errors = {
  8.         :no_response => 'does not respond to "%s"' % property,
  9.         :bang => 'Can not execute bang method on objects that do not respond to "save" method'
  10.       }
  11.  
  12.       raise '%s %s' % [self.class.name, errors[:no_response]] unless self.respond_to?(property)
  13.       raise '%s %s' % [sibling.class.name, errors[:no_response]] unless sibling.respond_to?(property)
  14.       raise errors[:bang] if is_bang && (!self.respond_to?('save') || !sibling.respond_to?('save'))
  15.  
  16.       old_sibling_property = sibling.send(property)
  17.  
  18.       sibling.send("#{property}=", self.send(property))
  19.       self.send("#{property}=", old_sibling_property)
  20.  
  21.       [self, sibling].collect(&:save) if is_bang
  22.       return self
  23.     end
  24.   end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement