Advertisement
Guest User

Untitled

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