Class: PhantomObject

Inherits:
Object
  • Object
show all
Defined in:
lib/phantom-object.rb

Instance Method Summary collapse

Constructor Details

#initialize(args = {}) ⇒ PhantomObject

Returns a new instance of PhantomObject.



4
5
6
# File 'lib/phantom-object.rb', line 4

def initialize args = {}
  assign_attributes args
end

Instance Method Details

#assign_attributes(args = {}) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/phantom-object.rb', line 8

def assign_attributes args = {}
  args.each do |key, value|
    raise ArgumentError, 'Your hash has keys with whitespaces' if key.match(/\s/i)
    raise ArgumentError, 'Your hash has keys with Capital letters at the beginning' if key.match(/\A[A-Z]/)
    self.class.class_eval("attr_accessor :#{key}") unless self.respond_to?(key.to_sym)
    if value.is_a?(Array)
      self.send("#{key}=", value.map{ |v| self.class.new(v) })
    elsif value.is_a?(Hash)
      self.send("#{key}=", self.class.new(value))
    else
      self.send("#{key}=", value.is_a?(String) ? value.strip : value)
    end
  end
end