Class: KtDataClass::Base

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

Instance Method Summary collapse

Constructor Details

#initialize(*args, **kwargs) ⇒ Base

Returns a new instance of Base.



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# File 'lib/kt_data_class/base.rb', line 3

def initialize(*args, **kwargs)
  unless args.empty?
    raise ArgumentError.new("data class must be initialized with keyword arguments.")
  end

  (self.class.definition.keys - kwargs.keys).each do |missing_key|
    raise ArgumentError.new("missing keyword: #{missing_key}")
  end
  (kwargs.keys - self.class.definition.keys).each do |unknown_key|
    raise ArgumentError.new("unknown keyword: #{unknown_key}")
  end

  kwargs.each do |attr_name, value|
    instance_variable_set("@#{attr_name}", value)
  end
end

Instance Method Details

#==(other) ⇒ Object



49
50
51
# File 'lib/kt_data_class/base.rb', line 49

def ==(other)
  self.hash == other.hash
end

#copy(*args, **kwargs) ⇒ Object



20
21
22
23
24
25
26
# File 'lib/kt_data_class/base.rb', line 20

def copy(*args, **kwargs)
  unless args.empty?
    raise ArgumentError.new("parameters for copying must be keyword arguments.")
  end
  new_params = hash.merge(kwargs)
  self.class.new(**new_params)
end

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


53
54
55
# File 'lib/kt_data_class/base.rb', line 53

def eql?(other)
  self.class == other.class && self.hash.eql?(other.hash)
end

#hashObject Also known as: to_h, to_hash



28
29
30
31
32
33
# File 'lib/kt_data_class/base.rb', line 28

def hash
  self.class.definition.keys.inject(Hash.new) do |h, attr_name|
    h[attr_name] = instance_variable_get("@#{attr_name}")
    h
  end
end

#to_aryObject Also known as: to_a



38
39
40
41
42
# File 'lib/kt_data_class/base.rb', line 38

def to_ary
  self.class.definition.keys.map do |attr_name|
    instance_variable_get("@#{attr_name}")
  end
end

#to_sObject



45
46
47
# File 'lib/kt_data_class/base.rb', line 45

def to_s
  hash.to_s
end