lib/eco/data/locations/node_base.rb in eco-helpers-2.6.4 vs lib/eco/data/locations/node_base.rb in eco-helpers-2.7.0

- old
+ new

@@ -8,20 +8,20 @@ require_relative 'node_base/serial' require_relative 'node_base/csv_convert' require_relative 'node_base/builder' extend Eco::Data::Locations::NodeBase::Builder - ALL_ATTRS = [] + ALL_ATTRS = [].freeze attr_accessor :tracked_level, :parent def copy - self.class.new.set_attrs(**self.to_h) + self.class.new.set_attrs(**to_h) end def attr(sym) - self.send(sym.to_sym) + send(sym.to_sym) end def attr?(sym) !attr(sym).to_s.strip.empty? end @@ -30,14 +30,25 @@ kargs.each {|attr, value| set_attr(attr, value)} self end def set_attr(attr, value) - self.send("#{attr}=", value) + send("#{attr}=", value) end def values_at(*attrs) attrs.map {|a| attr(a)} + end + + # @yield [node, json] optional custom serializer + # @yieldparam node [Node] self + # @yieldparam json [Hash] the default serialization + # @yieldreturn [Hash] the serialized Node + def node_hash(stringify_keys: true) + json = to_h(:id, :name, :parent_id) + json.transform_keys!(&:to_s) if stringify_keys + json.merge!(yield(self, json)) if block_given? + json end def to_h(*attrs) attrs = self.class::ALL_ATTRS if attrs.empty? attrs.zip(values_at(*attrs)).to_h