module InstVarsToHash

This module will allow you to properly to_s, to_h, and to_json on classes in which it is included.

It is not intended to be general purpose, but rather should be used only with standards and standards-related data structures, which themselves are mirrors of the JSON definitions used by Academic Benchmarks

Public Instance Methods

to_h(omit_parent: true, omit_empty_children: true) click to toggle source
# File lib/academic_benchmarks/lib/inst_vars_to_hash.rb, line 19
def to_h(omit_parent: true, omit_empty_children: true)
  retval = {}
  instance_variables.each do |iv|
    # Don't hashify these attributes, otherwise it can lead to infinite recursion
    next if %w[@authority @document @publication @section].include? iv.to_s
    if !(skip_parent?(omit_parent, iv) || skip_children?(omit_empty_children, iv))
      retval[iv.to_s.delete('@').to_sym] = elem_to_h(instance_variable_get(iv))
    end
  end
  retval
end
to_json(omit_parent: true, omit_empty_children: true) click to toggle source
# File lib/academic_benchmarks/lib/inst_vars_to_hash.rb, line 31
def to_json(omit_parent: true, omit_empty_children: true)
  to_h(
    omit_parent: omit_parent,
    omit_empty_children: omit_empty_children
  ).to_json
end
to_s(omit_parent: true, omit_empty_children: true) click to toggle source
# File lib/academic_benchmarks/lib/inst_vars_to_hash.rb, line 12
def to_s(omit_parent: true, omit_empty_children: true)
  to_h(
    omit_parent: omit_parent,
    omit_empty_children: omit_empty_children
  ).to_s
end

Private Instance Methods

elem_to_h(elem) click to toggle source
# File lib/academic_benchmarks/lib/inst_vars_to_hash.rb, line 48
def elem_to_h(elem)
  if elem.class == Array
    elem.map { |el| elem_to_h(el) }
  elsif expandable_to_hash(elem.class)
    elem.to_h
  else
    elem
  end
end
expandable_classes() click to toggle source
# File lib/academic_benchmarks/lib/inst_vars_to_hash.rb, line 40
def expandable_classes
  [ Hash, InstVarsToHash ]
end
expandable_to_hash(klass) click to toggle source
# File lib/academic_benchmarks/lib/inst_vars_to_hash.rb, line 44
def expandable_to_hash(klass)
  expandable_classes.any?{ |k| klass == k || klass < k }
end
skip_children?(omit_empty_children, iv) click to toggle source
# File lib/academic_benchmarks/lib/inst_vars_to_hash.rb, line 62
def skip_children?(omit_empty_children, iv)
  omit_empty_children && (iv =~ /^@?children$/i) && instance_variable_get(iv).empty?
end
skip_parent?(omit_parent, iv) click to toggle source
# File lib/academic_benchmarks/lib/inst_vars_to_hash.rb, line 58
def skip_parent?(omit_parent, iv)
  omit_parent && (iv =~ /^@?parent$/i)
end