Guest User

Untitled

a guest
Dec 13th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1.  
  2. # Some code that lets you quickly erect objects and their attributes with a params hash
  3.  
  4. class InvalidAutoInitializeParamError < StandardError; end
  5.  
  6. class Object
  7. class << self
  8. alias new_without_auto_initialize new
  9. def new_with_auto_initialize(*args,&block)
  10. a1 = args.first
  11. o = new_without_auto_initialize
  12. if a1.class==Hash
  13. if o.respond_to?(:initialize_with_hash)
  14. a1.keys.each do |k|
  15. setter = (k.to_s << '=').to_sym
  16. if o.respond_to? k || o.respond_to?(setter) # for now, only allow keys that have accessors
  17. if o.respond_to?(setter)
  18. o.send(setter, a1[k])
  19. else
  20. o.instance_variable_set("@#{k}".to_sym, a1[k])
  21. end
  22. else # don't allow it
  23. raise InvalidAutoInitializeParamError, "The auto initialize parameter '#{k}' is not allowed for this object"
  24. end
  25. end
  26. if o.method(:initialize_with_hash).arity >= 1
  27. o.initialize_with_hash(*args, &block)
  28. else
  29. o.initialize_with_hash(&block)
  30. yield o if block_given?
  31. end
  32. end
  33. end
  34. o
  35. end
  36. alias new new_with_auto_initialize
  37. end
  38. end
  39.  
  40. class Class
  41. def initialize_with_hash
  42. self.send(:define_method, :initialize_with_hash){}
  43. end
  44. end
  45.  
  46. class A
  47. attr_reader :this, :that
  48. def initialize_with_hash
  49. p instance_variables
  50. end
  51. end
  52.  
  53. class B
  54. attr_accessor :whoa_dude
  55. initialize_with_hash
  56. end
  57.  
  58. a = A.new({this: 5, that: 10}){ |a| p a }
  59.  
  60. b = B.new(whoa_dude: 'yeah')
  61.  
  62. p b
  63.  
  64. #=> [:@this, :@that]
  65. #=> #<A:0x007ff6c2884698 @this=5, @that=10>
  66. #=> #<B:0x007ff6c2884288 @whoa_dude="yeah">
  67.  
  68. a = A.new({this: 5, that: 10, those: 7})
  69.  
  70. #=> The auto initialize parameter 'those' is not allowed for this object (InvalidAutoInitializeParamError)
Add Comment
Please, Sign In to add comment