Advertisement
Guest User

Untitled

a guest
Aug 29th, 2016
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.69 KB | None | 0 0
  1. class Class
  2.  
  3. def attr_accessor_with_history(attr_name)
  4. attr_name = attr_name.to_s
  5. attr_hist_name = attr_name+'_history'
  6.  
  7. #getter
  8. self.class_eval("def #{attr_name};@#{attr_name};end")
  9.  
  10. #setter
  11. self.class_eval %Q{
  12. def #{attr_name}=(val)
  13. # add to history
  14. @#{attr_hist_name} = [nil] if @#{attr_hist_name}.nil?
  15. @#{attr_hist_name} << val
  16.  
  17. # set the value itself
  18. @#{attr_name}=val
  19. end
  20.  
  21. def #{attr_hist_name};@#{attr_hist_name};end
  22.  
  23. }
  24.  
  25. end
  26.  
  27. end
  28. class Foo
  29. attr_accessor_with_history :bar
  30.  
  31. end
  32.  
  33. f = Foo.new
  34. f.bar = 3
  35. f.bar = :wowzo
  36. f.bar = 'boo!'
  37. puts f.bar_history
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement