Class: KtDataClass::Base
- Inherits:
-
Object
- Object
- KtDataClass::Base
- Defined in:
- lib/kt_data_class/base.rb
Instance Method Summary collapse
- #==(other) ⇒ Object
- #copy(*args, **kwargs) ⇒ Object
- #eql?(other) ⇒ Boolean
- #hash ⇒ Object (also: #to_h, #to_hash)
-
#initialize(*args, **kwargs) ⇒ Base
constructor
A new instance of Base.
- #to_ary ⇒ Object (also: #to_a)
- #to_s ⇒ Object
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
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 |
#hash ⇒ Object 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_ary ⇒ Object 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_s ⇒ Object
45 46 47 |
# File 'lib/kt_data_class/base.rb', line 45 def to_s hash.to_s end |