Module: DataClass

Defined in:
lib/emery/dataclass.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



46
47
48
# File 'lib/emery/dataclass.rb', line 46

def self.included(base)
  base.extend ClassMethods
end

Instance Method Details

#==(other) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/emery/dataclass.rb', line 9

def ==(other)
  begin
    T.check(self.class, other)
    self.class.typed_attributes.keys.each do |attr|
      if self.instance_variable_get("@#{attr}") != other.instance_variable_get("@#{attr}")
        return false
      end
    end
    return true
  rescue
    return false
  end
end

#copy(params) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/emery/dataclass.rb', line 23

def copy(params)
  params.keys.each do |attr|
    if !self.class.typed_attributes.key?(attr)
      raise TypeError.new("Non existing attribute #{attr}")
    end
  end
  new_params =
    self.class.typed_attributes.keys.map do |attr|
      attr_value =
        if params.key?(attr)
          params[attr]
        else
          self.instance_variable_get("@#{attr}")
        end
      [attr, attr_value]
    end.to_h
  return self.class.new(new_params)
end

#initialize(params) ⇒ Object



2
3
4
5
6
7
# File 'lib/emery/dataclass.rb', line 2

def initialize(params)
  self.class.typed_attributes.each do |attr, attr_type|
    attr_value = params[attr]
    self.instance_variable_set("@#{attr}", T.check_var(attr, attr_type, attr_value))
  end
end

#to_jsonObject



42
43
44
# File 'lib/emery/dataclass.rb', line 42

def to_json
  return Jsoner.serialize(self.class, self)
end