77 lines
1.5 KiB
Ruby
77 lines
1.5 KiB
Ruby
# frozen_string_literal: true
|
|
# require "sequel"
|
|
|
|
class SpaceTraders::Model
|
|
def self.attributes(*list)
|
|
list.each { attribute(_1) }
|
|
define_method("attributes") do
|
|
list
|
|
end
|
|
end
|
|
|
|
def self.attribute(name)
|
|
define_method(name) do
|
|
instance_variable_get("@#{name}")
|
|
end
|
|
|
|
define_method("#{name}=") do |value|
|
|
instance_variable_set("@#{name}", value)
|
|
end
|
|
end
|
|
|
|
# it's recursive
|
|
def to_h
|
|
self.attributes.to_h do |k|
|
|
v = self[k]
|
|
v = v.to_h if v.is_a?(SpaceTraders::Model)
|
|
v = v.map { _1.to_h } if v.is_a?(Array) && v.first.is_a?(SpaceTraders::Model)
|
|
[
|
|
k,
|
|
v,
|
|
]
|
|
end
|
|
end
|
|
|
|
def initialize(client, **attrs)
|
|
raise "Cannot use model with client parse disabled" if !client.parse?
|
|
|
|
@_client = client
|
|
attrs.each { self.send("#{_1}=", _2) }
|
|
end
|
|
|
|
def [](k)
|
|
if attributes.include?(k) || attributes.include?(k.to_s) || attributes.include?(k.to_sym)
|
|
instance_variable_get("@#{k}")
|
|
else
|
|
raise "Invalid attribute #{k}"
|
|
end
|
|
end
|
|
|
|
def []=(k, v)
|
|
if attributes.include?(k) || attributes.include?(k.to_s) || attributes.include?(k.to_sym)
|
|
instance_variable_set("@#{k}", v)
|
|
else
|
|
raise "Invalid attribute #{k}"
|
|
end
|
|
end
|
|
|
|
def client
|
|
@_client
|
|
end
|
|
|
|
def update(**params)
|
|
params = client.data if params.empty?
|
|
|
|
attributes.each do
|
|
if params[_1]
|
|
self[_1] = _2
|
|
end
|
|
end
|
|
end
|
|
end
|
|
|
|
Dir['lib/models/*.rb'].each do
|
|
load _1
|
|
SpaceTraders::Log.warn("load #{_1}")
|
|
end
|