Sha256: 632dc7c229cb5566a9c39f022a3e71e5b5f483c78df12d0d78ff9ef972694830

Contents?: true

Size: 1.83 KB

Versions: 7

Compression:

Stored size: 1.83 KB

Contents

module Expressir
  module Model
    class ModelElement
      CLASS_KEY = '_class' 

      def to_hash(options = {})
        skip_empty = options[:skip_empty]

        instance_variables.select{|x| x != :@parent}.each_with_object({ CLASS_KEY => self.class.name }) do |variable, result|
          key = variable.to_s.sub(/^@/, '')
          value = instance_variable_get(variable)

          # skip default values (nil, empty array)
          if !skip_empty or !(value.nil? or (value.is_a? Array and value.count == 0))
            result[key] = if value.is_a? Array
              value.map do |value|
                if value.is_a? ModelElement
                  value.to_hash(options)
                else
                  value
                end
              end
            elsif value.is_a? ModelElement
              value.to_hash(options)
            else
              value
            end
          end
        end
      end

      def self.from_hash(hash)
        node_class = hash[CLASS_KEY]
        node_options = hash.select{|x| x != CLASS_KEY}.each_with_object({}) do |(variable, value), result|
          key = variable.to_sym

          result[key] = if value.is_a? Array
            value.map do |value|
              if value.is_a? Hash
                self.from_hash(value)
              else
                value
              end
            end
          elsif value.is_a? Hash
            self.from_hash(value)
          else
            value
          end
        end

        node = Object.const_get(node_class).new(node_options)

        # attach parent
        if node.class.method_defined? :children
          node.children.each do |child_node|
            if child_node.class.method_defined? :parent and !child_node.parent
              child_node.parent = node
            end
          end
        end

        node
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
expressir-0.2.10 lib/expressir/model/model_element.rb
expressir-0.2.10-x86_64-linux lib/expressir/model/model_element.rb
expressir-0.2.10-x86_64-darwin lib/expressir/model/model_element.rb
expressir-0.2.10-x86-mingw32 lib/expressir/model/model_element.rb
expressir-0.2.10-x86-linux lib/expressir/model/model_element.rb
expressir-0.2.10-x64-mingw32 lib/expressir/model/model_element.rb
expressir-0.2.10-arm64-darwin lib/expressir/model/model_element.rb