Sha256: 1c31c51d65e4b3a211f6a33ddd0ec5d710c386daf34329304cab82d517d2130f

Contents?: true

Size: 1.14 KB

Versions: 1

Compression:

Stored size: 1.14 KB

Contents

# frozen_string_literal: true

# copied from https://dev.to/ayushn21/how-to-generate-yaml-from-ruby-objects-without-type-annotations-4fli
module Storazzo
  module Hashify
    # Classes that include this module can exclude certain
    # instance variable from its hash representation by overriding
    # this method
    def ivars_excluded_from_hash
      ['this_doesnt_exist']
    end

    def to_hash
      hash = {}
      excluded_ivars = ivars_excluded_from_hash

      # Iterate over all the instance variables and store their
      # names and values in a hash
      instance_variables.each do |var|
        next if excluded_ivars.include? var.to_s

        value = instance_variable_get(var)
        value = value.map(&:to_hash) if value.is_a? Array

        hash[var.to_s.delete('@')] = value
      end

      hash
    end

    def obj_to_hash
      h = {}
      puts self
      instance_variables.each do |var|
        # puts var
        h[var.to_s.delete('@')] = instance_variable_get(var) # send(var.to_s.delete('@'))
      end
      h
    end

    def to_yaml
      to_hash.to_yaml
    end

    def obj_to_yaml
      obj_to_hash.to_yaml
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
storazzo-0.6.1 lib/storazzo/hashify.rb