Module: FlexTrans::Struct

Defined in:
lib/flex_trans/struct.rb

Class Method Summary collapse

Class Method Details

.new(*args, &block) ⇒ Object



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
33
34
# File 'lib/flex_trans/struct.rb', line 3

def self.new(*args, &block)
  klass = Class.new do
    @@attributes = []

    class << self
      def set_attrributes(*attributes)
        @@attributes ||= []
        @@attributes.concat(attributes)
        attr_reader(*attributes)
      end
    end

    set_attrributes(*args)

    def initialize(attributes)
      shortage_attributes = @@attributes - attributes.keys
      if shortage_attributes.any?
        raise ArgumentError, "Some attributes doesn't given: #{shortage_attributes}"
      end

      attributes.each do |name, value|
        instance_variable_set(:"@#{name}", value)
      end
    end
  end

  if block_given?
    klass.class_eval(&block)
  end

  klass
end