Advertisement
Guest User

Untitled

a guest
May 22nd, 2018
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  1. class Factory
  2. include Enumerable
  3.  
  4. class << self
  5. def new(*attrs, &block)
  6. class_name = attrs.shift if attrs[0].is_a?(String)
  7. my_struct_class = Class.new(self) do
  8. def initialize(*attrs, &block)
  9. attr_accessor(*attrs)
  10.  
  11. define_method :initialize do |*values|
  12. values.each_with_index { |value, i| send("#{attrs[i]}=", value) }
  13. end
  14.  
  15. define_method :[] do |attribute|
  16. if attribute.is_a? Numeric
  17. send("#{attributes[attribute]}")
  18. else
  19. send(attribute)
  20. end
  21. end
  22. class_eval(&block) if block_given?
  23.  
  24. # redefinition of the method new, so that the heresy did not happen
  25. # struct_class is a subclass of Factory , so we had to redefine method :new
  26. my_struct_class.define_singleton_method(:new, Object.method(:new))
  27. class_name ? const_set(class_name.to_s, my_struct_class) : my_struct_class
  28. end
  29. end
  30. end
  31. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement