Class: Hash

Inherits:
Object
  • Object
show all
Defined in:
ext/hash.rb

Overview

Supports converting Hashes in to different kinds of structs via a ‘to_struct’ method.

Note: ClassyStruct perferred over OpenStruct, it’s faster.

Constant Summary collapse

@@struct_type =
ClassyStruct::STRUCT_TYPE

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#struct_typeObject

Return struct type for instance.

Example:

hash = { :foo => :bar }

# default
hash.struct_type
#=> :classy_struct


69
70
71
# File 'ext/hash.rb', line 69

def struct_type
  @struct_type
end

Class Method Details

.struct_typeObject

Return struct type for class.

Example:

Hash.struct_type
#=> :classy_struct


80
81
82
# File 'ext/hash.rb', line 80

def self.struct_type
  @@struct_type
end

.struct_type=(type) ⇒ Object

Set struct type for class.

Example:

Hash.struct_type = :struct
Hash.struct_type
#=> :struct
hash = { :foo => :bar }
hash.struct_type
#=> :struct


94
95
96
97
98
99
# File 'ext/hash.rb', line 94

def self.struct_type= type
  type = type.to_sym
  raise "Invalid struct type: #{type}." unless struct_types.include?(type)

  @@struct_type = type.to_sym
end

Instance Method Details

#to_struct(type = nil) ⇒ Object

Convert Hash to Struct, OpenStruct or ClassyStruct

Example:

hash = { :foo => :bar }

# default
s = hash.to_struct(:classy_struct)
s.class
#=> ClassyHashStruct
hash.foo
#=> :bar

s = hash.to_struct(:struct)
s.class
#=> Struct

s = hash.to_struct(:open_struct)
s.class
#=> OpenStruct


33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'ext/hash.rb', line 33

def to_struct(type=nil)
  self.struct_type = type.nil? ? struct_type : type.to_sym

  if struct_type == ClassyStruct::STRUCT_TYPE
    begin
      Object.send(:remove_const, ClassyStruct::CLASS_NAME)
    rescue; end

    return Object.const_set(ClassyStruct::CLASS_NAME, ClassyStruct.new).new(self)
  end

  self.each do |k,v|
    self[k] = v.to_struct(struct_type) if v.is_a? Hash
  end

  if struct_type == OpenStruct::STRUCT_TYPE
    # openstruct is said to be slower, so giving the option to disable
    return OpenStruct.new(self)
  end

  # otherwise use standard struct
  return nil if self.empty?

  klass = Struct.new(*keys.map{|key| key.to_sym})
  klass.new(*values)
end