Class: BitcoinNode::Protocol::Payload
- Inherits:
-
Object
- Object
- BitcoinNode::Protocol::Payload
show all
- Defined in:
- lib/bitcoin_node/protocol.rb
Class Method Summary
collapse
Instance Method Summary
collapse
Constructor Details
#initialize(attributes = {}) ⇒ Payload
Returns a new instance of Payload.
151
152
153
154
155
156
157
158
159
160
|
# File 'lib/bitcoin_node/protocol.rb', line 151
def initialize(attributes = {})
attributes.each do |k,v|
self.send("#{k}=", v)
end
missings = self.class.field_names - attributes.keys
missings.each do |k|
d = self.class.defaults[k]
self.send("#{k}=", Proc === d ? d.call : d)
end
end
|
Class Method Details
.defaults ⇒ Object
124
125
126
|
# File 'lib/bitcoin_node/protocol.rb', line 124
def defaults
@defaults ||= {}
end
|
.field(name, type, options = {}) ⇒ Object
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
|
# File 'lib/bitcoin_node/protocol.rb', line 107
def field(name, type, options = {})
define_method(name) do
instance_fields[name]
end
define_method("#{name}=") do |value|
if type === value
instance_fields[name] = value
else
instance_fields[name] = type.new(*Array(value))
end
end
fields[name] = type
defaults[name] = options[:default] if options[:default]
end
|
.field_names ⇒ Object
132
133
134
|
# File 'lib/bitcoin_node/protocol.rb', line 132
def field_names
fields.keys
end
|
.fields ⇒ Object
128
129
130
|
# File 'lib/bitcoin_node/protocol.rb', line 128
def fields
@fields ||= {}
end
|
.parse(payload) ⇒ Object
136
137
138
139
140
141
142
143
144
145
146
147
148
|
# File 'lib/bitcoin_node/protocol.rb', line 136
def parse(payload)
result = fields.inject({}) do |memo, (field_name, type)|
custom_parse_method = "parse_#{field_name.to_s}"
parsed, payload = if respond_to?(custom_parse_method)
public_send(custom_parse_method, payload, memo)
else
type.parse(payload)
end
memo[field_name] = parsed
memo
end
new(result)
end
|
Instance Method Details
#bytesize ⇒ Object
169
170
171
|
# File 'lib/bitcoin_node/protocol.rb', line 169
def bytesize
raw.bytesize
end
|
#name ⇒ Object
177
178
179
|
# File 'lib/bitcoin_node/protocol.rb', line 177
def name
type.downcase
end
|
#raw ⇒ Object
162
163
164
165
166
167
|
# File 'lib/bitcoin_node/protocol.rb', line 162
def raw
@raw ||= begin
ordered = instance_fields.values_at(*self.class.field_names)
ordered.map(&:pack).join
end
end
|
#to_s ⇒ Object
Also known as:
inspect
181
182
183
|
# File 'lib/bitcoin_node/protocol.rb', line 181
def to_s
"#<#{type} #{@instance_fields.inspect}>"
end
|
#type ⇒ Object
173
174
175
|
# File 'lib/bitcoin_node/protocol.rb', line 173
def type
self.class.name.split('::').last
end
|