Module: Objectify::ClassMethods

Defined in:
lib/objectify.rb

Instance Method Summary collapse

Instance Method Details

#object(name, attrs: []) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/objectify.rb', line 22

def object(name, attrs:[])
  klass = Class.new Object
  className = String(name).camelize
  nameString = String(name)

  attrs.each do |attr|
    if attr.is_a? Hash
      klass.class_eval <<-EOS
        def #{attr.keys.first.to_s}
          instance_eval #{attr.values.first}
        end
      EOS
    else
      klass.class_eval <<-EOS
        attr_reader :#{attr}
        attr_accessor :#{attr}
      EOS
    end
  end
  
  self.class_eval <<-EOS
    class << self
      def #{nameString}(#{attrs.map{ |a| "#{String(a)}: nil" }.join(', ')})
        item = #{className}.new(#{attrs.map{ |a| "#{String(a)}: #{String(a)}" }.join(', ')})
        Objectify.#{nameString.pluralize}.push(item)
        item
      end
    end
  EOS

  self.const_set className, klass
  Objectify::register_object name
end