Sha256: b41482f51c7c6da4a76cbc1d13354c7053cf55ec1d4fd628a1bf5c942dec60e2

Contents?: true

Size: 1.87 KB

Versions: 7

Compression:

Stored size: 1.87 KB

Contents

module Expressir
  module Model
    class ModelElement
      CLASS_KEY = '_class'
      SOURCE_KEY = 'source'

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

        hash = {}
        hash[CLASS_KEY] = self.class.name

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

          # skip empty 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

        if formatter
          hash[SOURCE_KEY] = formatter.format(self)
        end

        hash
      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)

        if node.class.method_defined? :attach_parent_to_children
          node.attach_parent_to_children
        end

        node
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

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