Module: Serializable

Included in:
ComplexMove, Entity
Defined in:
lib/game_2d/serializable.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.as_json(thing) ⇒ Object

Returns a hash which becomes the JSON



23
24
25
# File 'lib/game_2d/serializable.rb', line 23

def self.as_json(thing)
  { :class => thing.class.to_s }
end

.from_json(json, generate_id = false) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/game_2d/serializable.rb', line 40

def self.from_json(json, generate_id=false)
  return nil unless json
  class_name = json[:class]
  binding.pry unless class_name
  raise "Suspicious class name: #{class_name}" unless
    (class_name == 'Player') ||
    (class_name.start_with? 'Entity::') ||
    (class_name.start_with? 'Move::')
  require "game_2d/#{class_name.pathize}"
  clazz = constant(class_name)
  it = clazz.new

  # A registry ID must be specified either in the JSON or by the caller, but
  # not both
  if it.is_a? Registerable
    if generate_id
      fail("Entity #{it} (from #{json.inspect}) already has " +
        "ID #{it.registry_id}, cannot generate") if it.registry_id?
      # Leave it nil - it will be populated when added to a space
    else
      it.registry_id = json[:registry_id]
    end
  elsif generate_id
    fail("#{clazz} is not Registerable")
  end

  it.update_from_json(json)
end

Instance Method Details

#<=>(other) ⇒ Object

Based on all_state



13
14
15
# File 'lib/game_2d/serializable.rb', line 13

def <=>(other)
  self.all_state <=> other.all_state
end

#==(other) ⇒ Object



16
17
18
# File 'lib/game_2d/serializable.rb', line 16

def ==(other)
  other.class.equal?(self.class) && other.all_state == self.all_state
end

#all_stateObject

Flat list of all object state For sorting purposes, most significant goes first



8
9
10
# File 'lib/game_2d/serializable.rb', line 8

def all_state
  []
end

#eql?(other) ⇒ Boolean

Returns:

  • (Boolean)


20
# File 'lib/game_2d/serializable.rb', line 20

def eql?(other); self == other; end

#hashObject



19
# File 'lib/game_2d/serializable.rb', line 19

def hash; self.class.hash ^ all_state.hash; end

#to_json(*args) ⇒ Object

Based on as_json



28
29
30
# File 'lib/game_2d/serializable.rb', line 28

def to_json(*args)
  as_json.to_json(*args)
end

#to_sObject



36
37
38
# File 'lib/game_2d/serializable.rb', line 36

def to_s
  self.class.name
end

#update_from_json(hash) ⇒ Object

Make our state match what’s in the hash



33
34
# File 'lib/game_2d/serializable.rb', line 33

def update_from_json(hash)
end