Module: ActiveModel::Serializers::Binary
- Extended by:
- ActiveSupport::Concern
- Includes:
- ActiveModel::Serialization, DataTypes
- Defined in:
- lib/active_model_serializers_binary/active_model_serializers_binary.rb
Overview
Active Model Binary serializer
Defined Under Namespace
Modules: ClassMethods Classes: Serializer
Instance Method Summary collapse
-
#from_bytes(buffer, options = {}) { ... } ⇒ Object
(also: #load)
Sets the model
attributesfrom an Binary string. - #from_words(buffer = [], options = {}, &block) ⇒ Object
- #size(options = {}) ⇒ Object
-
#to_bytes(options = {}, &block) ⇒ Object
(also: #dump)
Returns a binary array representing the model.
- #to_words(options = {}, &block) ⇒ Object
Instance Method Details
#from_bytes(buffer, options = {}) { ... } ⇒ Object Also known as: load
Sets the model attributes from an Binary string. Returns self.
class Person
include ActiveModel::Serializers::Binary
attr_accessor :name, :age, :awesome
def attributes=(hash)
hash.each do |key, value|
instance_variable_set("@#{key}", value)
end
end
def attributes
instance_values
end
char :name, count: 1, length: 10
int16 :age
bool :awesome
end
bytes = [98, 111, 98, 0, 0, 0, 0, 0, 0, 0, 22, 0, 1]
person = Person.new
person.from_bytes(bytes) do |p|
p.name.upcase!
end
=> #<Person:0x007fec5e3b3c40 @age=22, @awesome=true, @name="bob">
343 344 345 346 347 348 349 350 351 352 353 354 |
# File 'lib/active_model_serializers_binary/active_model_serializers_binary.rb', line 343 def from_bytes(buffer, = {}, &block) = { :align => true } = .deep_merge() retVal = Serializer.new(self, ).load buffer if block_given? yield self end retVal end |
#from_words(buffer = [], options = {}, &block) ⇒ Object
358 359 360 361 |
# File 'lib/active_model_serializers_binary/active_model_serializers_binary.rb', line 358 def from_words(buffer = [], = {}, &block) data = buffer.pack('v*').unpack('C*') from_bytes(data, , &block) end |
#size(options = {}) ⇒ Object
363 364 365 366 367 368 369 |
# File 'lib/active_model_serializers_binary/active_model_serializers_binary.rb', line 363 def size( = {}) = { :align => true } = .deep_merge() Serializer.new(self, ).size end |
#to_bytes(options = {}, &block) ⇒ Object Also known as: dump
Returns a binary array representing the model. Configuration can be passed through options.
person = Person.find(1)
person.to_bytes
=> [98, 111, 98, 0, 0, 0, 0, 0, 0, 0, 22, 0, 1]
288 289 290 291 292 293 294 295 296 297 |
# File 'lib/active_model_serializers_binary/active_model_serializers_binary.rb', line 288 def to_bytes( = {}, &block) = { :align => true, } = .deep_merge() if block_given? yield self end Serializer.new(self, ).dump end |
#to_words(options = {}, &block) ⇒ Object
301 302 303 304 305 |
# File 'lib/active_model_serializers_binary/active_model_serializers_binary.rb', line 301 def to_words( = {}, &block) data = to_bytes(, &block) byte_count = (data.count/2.0).ceil*2 data.fill(0, data.count...byte_count).pack('C*').unpack('v*') end |