Class: Data

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**kwargs) ⇒ Data

Returns a new instance of Data.



57
58
59
# File 'lib/data.rb', line 57

def initialize(**kwargs)
  @attributes = Hash[members.map {|m| [m,kwargs[m]] }]
end

Class Method Details

.define(*args, &block) ⇒ Object

Raises:

  • (ArgumentError)


14
15
16
17
18
19
20
21
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
# File 'lib/data.rb', line 14

def self.define(*args, &block)
  raise ArgumentError if args.any?(/=/)
  klass = ::Class.new(self, &block)

  if args.first.is_a?(String)
    name = args.shift
    Data.const_set(name, klass)
  end

  klass.define_singleton_method(:members) { args.map{ _1.intern } }

  klass.define_singleton_method(:new) do |*new_args, **new_kwargs, &block|

    init_kwargs = if new_args.any?
      Hash[members.take(new_args.size).zip(new_args)]
    else
      new_kwargs
    end

    self.allocate.tap do |instance|
      instance.send(:initialize, **init_kwargs, &block)
    end.freeze
  end
  class << klass
    alias_method :[], :new
  end

  args.map do |arg|
    if klass.method_defined?(arg)
      raise ArgumentError, "duplicate member #{arg}"
    end
    klass.define_method(arg) do
      @attributes[arg]
    end
  end

  klass
end

Instance Method Details

#==(other) ⇒ Object



84
85
86
# File 'lib/data.rb', line 84

def ==(other)
  self.class == other.class && to_h == other.to_h
end

#deconstructObject



61
62
63
# File 'lib/data.rb', line 61

def deconstruct
  @attributes.values
end

#deconstruct_keys(array) ⇒ Object

Raises:

  • (TypeError)


65
66
67
68
69
70
# File 'lib/data.rb', line 65

def deconstruct_keys(array)
  raise TypeError unless array.is_a?(Array) || array.nil?
  return @attributes if array&.first.nil?

  @attributes.slice(*array)
end

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


80
81
82
# File 'lib/data.rb', line 80

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

#hashObject



76
77
78
# File 'lib/data.rb', line 76

def hash
  to_h.hash
end

#inspectObject Also known as: to_s



88
89
90
91
92
93
94
95
# File 'lib/data.rb', line 88

def inspect
  name = ["data", self.class.name].compact.join(" ")
  attribute_markers = @attributes.map do |key, value|
    insect_key = key.to_s.start_with?("@") ? ":#{key}" : key
    "#{insect_key}=#{value}"
  end
  %(#<#{name} #{attribute_markers.join(", ")}>)
end

#membersObject



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

def members
  self.class.members
end

#to_h(&block) ⇒ Object



72
73
74
# File 'lib/data.rb', line 72

def to_h(&block)
  @attributes.to_h(&block)
end

#with(**kwargs) ⇒ Object



98
99
100
# File 'lib/data.rb', line 98

def with(**kwargs)
  self.class.new(**@attributes.merge(kwargs))
end