Class: ConstructorStruct

Inherits:
Object
  • Object
show all
Defined in:
lib/constructor_struct.rb

Class Method Summary collapse

Class Method Details

.new(*accessors, &block) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/constructor_struct.rb', line 2

def self.new(*accessors, &block)
  defaults = {:accessors => true, :strict => false}
  
  accessor_names = accessors.dup
  if accessors.last.is_a? Hash
    accessor_names.pop
    user_opts = accessors.last
    user_opts.delete(:accessors)
    defaults.each do |k,v|
      user_opts[k] ||= v
    end
  else
    accessors << defaults
  end
  
  Class.new do
    constructor *accessors

    class_eval(&block) if block

    comparator_code = accessor_names.map { |fname| "self.#{fname} == o.#{fname}" }.join(" && ")
    eval %|
      def ==(o)
        (self.class == o.class) && #{comparator_code}
      end
      def eql?(o)
        (self.class == o.class) && #{comparator_code}
      end
    |
  end
end