Class: Signalize::Struct

Inherits:
Object
  • Object
show all
Extended by:
Accessors
Defined in:
lib/signalize/struct.rb

Defined Under Namespace

Modules: Accessors

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Accessors

signal_accessor

Constructor Details

#initialize(**data) ⇒ Struct

Returns a new instance of Struct.



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/signalize/struct.rb', line 52

def initialize(**data)
  # The below code is all to replicate native Ruby ergonomics
  unknown_keys = data.keys - members
  unless unknown_keys.empty?
    plural_suffix = unknown_keys.length > 1 ? "s" : ""
    raise ArgumentError, "unknown keyword#{plural_suffix}: #{unknown_keys.map { ":#{_1}" }.join(", ")}"
  end

  missing_keys = members - data.keys
  unless missing_keys.empty?
    plural_suffix = missing_keys.length > 1 ? "s" : ""
    raise ArgumentError, "missing keyword#{plural_suffix}: #{missing_keys.map { ":#{_1}" }.join(", ")}"
  end

  # Initialize with keyword arguments
  data.each do |k, v|
    send("#{k}=", v)
  end
end

Class Method Details

.define(*names, &block) ⇒ Object



45
46
47
48
49
50
# File 'lib/signalize/struct.rb', line 45

def self.define(*names, &block)
  Class.new(self).tap do |struct|
    struct.signal_accessor(*names)
    struct.class_eval(&block) if block
  end
end

Instance Method Details

#deconstruct_keysObject



74
# File 'lib/signalize/struct.rb', line 74

def deconstruct_keys(...) = to_h.deconstruct_keys(...)

#inspectObject



78
79
80
81
82
83
84
85
# File 'lib/signalize/struct.rb', line 78

def inspect
  var_peeks = instance_variables.filter_map do |var_name|
    var = instance_variable_get(var_name)
    "#{var_name.to_s.delete_prefix("@")}=#{var.peek.inspect}" if var.is_a?(Signalize::Signal)
  end.join(", ")
  
  "#<#{self.class}#{var_peeks.empty? ? nil : " #{var_peeks}"}>"
end

#membersObject



72
# File 'lib/signalize/struct.rb', line 72

def members = self.class.members

#to_hObject



76
# File 'lib/signalize/struct.rb', line 76

def to_h = members.each_with_object({}) { _2[_1] = send("#{_1}_signal").peek }

#to_sObject



87
88
89
# File 'lib/signalize/struct.rb', line 87

def to_s
  inspect
end