Skip to content

Instantly share code, notes, and snippets.

@Ikariusrb
Created April 18, 2020 18:39
Show Gist options
  • Save Ikariusrb/c0b85c79b16b4f30b3d3bb35a26a1b5e to your computer and use it in GitHub Desktop.
Save Ikariusrb/c0b85c79b16b4f30b3d3bb35a26a1b5e to your computer and use it in GitHub Desktop.
EntityBackedObject - for DragonRuby to wrap an entity with a PORO easily
# MIT License
# Copyright (c) 2020 Ross Becker
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
module EntityBackedObject
def entity_delegate(*methods, to: nil)
method_names = methods.each_with_object([]) do |method, new_methods|
getter = method.to_sym
new_methods << define_method(getter) do
instance_variable_get("@entity").send(getter)
end
setter = "#{method}=".to_sym
new_methods << define_method(setter) do |val|
instance_variable_get("@entity").send(setter, val)
end
end
define_method(:initialize) do |entity, args = {}|
if entity.nil?
instance_variable_set('@entity', $gtk.args.state.new_entity_strict(to, args.merge(_ob_t_: self.class.name)))
else
instance_variable_set('@entity', entity)
end
end
define_method(:to_entity) do
instance_variable_get("@entity")
end
const_set('ENTITY_TYPE', to)
method_names
end
end
# Use:
#
# class Enemy
# extend EntityBackedObject
#
# entity_delegate :x, :y, :hp, :previous_hp, :max_hp, :is_dead, to: :enemy
# end
#
# def entity_to_object(entity)
# if entity._ob_t_
# klass = entity._ob_t_.split('::').reduce(Object) { |o, c| o.const_get(c) }
# klass.new(entity)
# else
# entity
# end
# end
#
# new_enemy = Enemy.new(nil, { x: 13, y: 5, previous_hp: 3, hp: 3, max_hp: 3, is_dead: false })
#
# to serialize: state.enemies.map(&:to_entity)
#
# to deserialize: state.enemies.map { |e| entity_to_object(e) }
#
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment