Module: Structure

Defined in:
lib/structure.rb,
lib/structure/double.rb

Overview

Structure

Defined Under Namespace

Modules: ClassMethods

Instance Method Summary collapse

Instance Method Details

#==(other) ⇒ Object Also known as: eql?


37
38
39
40
# File 'lib/structure.rb', line 37

def ==(other)
  return false unless other.respond_to?(:attributes)
  attributes == other.attributes
end

#attribute_namesObject


33
34
35
# File 'lib/structure.rb', line 33

def attribute_names
  self.class.attribute_names
end

#attributesObject Also known as: to_h


11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/structure.rb', line 11

def attributes
  attribute_names.reduce({}) do |hash, key|
    value = send(key)
    hash.update(
      key =>
        if value.respond_to?(:attributes)
          value.attributes
        elsif value.is_a?(Array)
          value.map do |element|
            if element.respond_to?(:attributes)
              element.attributes
            else
              element
            end
          end
        else
          value
        end
    )
  end
end

#inspectObject Also known as: to_s


42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/structure.rb', line 42

def inspect
  name = self.class.name || self.class.to_s.gsub(/[^\w:]/, "")
  values =
    attribute_names
    .map do |key|
      value = send(key)
      if value.is_a?(Array)
        description = value.take(3).map(&:inspect).join(", ")
        description += "..." if value.size > 3
        "#{key}=[#{description}]"
      else
        "#{key}=#{value.inspect}"
      end
    end
    .join(", ")

  "#<#{name} #{values}>"
end