Class: SDStruct

Inherits:
Object
  • Object
show all
Defined in:
lib/sd_struct/base.rb,
lib/sd_struct/version.rb,
lib/sd_struct/deep_search.rb,
lib/sd_struct/deep_convert.rb

Overview

Alternative to OpenStruct that is more strict and go deeper.

Author:

  • Adrian Setyadi

Constant Summary collapse

InspectKey =

:nodoc:

:__inspect_key__
VERSION =
"0.1.0"

Instance Method Summary collapse

Constructor Details

#initialize(hash = nil, deep = true) ⇒ SDStruct

Creates a new SDStruct object. By default, the resulting SDStruct object will have no attributes.

The optional hash, if given, will generate attributes and values (can be a Hash, an SDStruct or a Struct). For example:

require 'sd_struct' # or require 'sd_struct/base'
hash = { "name" => "Matz", "coding language" => :ruby, :age => "old" }
data = SDStruct.new(hash)

p data # -> #<SDStruct .name="Matz", ['coding language']=:ruby, .age="old">


45
46
47
48
49
50
51
52
53
# File 'lib/sd_struct/base.rb', line 45

def initialize(hash = nil, deep = true)
  @deep = deep
  @table = {}
  if hash
    hash.each_pair do |k, v|
      @table[new_struct_member(k)] = structurize(v) # @deep is used in this method
    end
  end
end

Instance Method Details

#==(other) ⇒ Object



168
169
170
171
# File 'lib/sd_struct/base.rb', line 168

def ==(other)
  return false unless other.kind_of?(self.class)
  @table == other.table
end

#[](name) ⇒ Object

Returns the value of a member.

person = SDStruct.new('name' => 'Matz', 'lang' => 'ruby')
person[:lang] # => ruby, same as person.lang


119
120
121
# File 'lib/sd_struct/base.rb', line 119

def [](name)
  @table.has_key?(name) ? @table[name] : @table[name.to_s.underscore.to_sym]
end

#[]=(name, value) ⇒ Object

Sets the value of a member.

person = SDStruct.new('name' => 'Matz', 'lang' => 'python')
person[:lang] = 'ruby' # => equivalent to person.lang = 'ruby'
person.lang # => ruby


130
131
132
133
134
135
# File 'lib/sd_struct/base.rb', line 130

def []=(name, value)
  unless self.[](name).nil? || value.is_a?(self.[](name).class)
    warn("You're assigning a value with different type as the previous value.")
  end
  @table[new_struct_member(name)] = structurize(value)
end

#delete_field(name) ⇒ Object Also known as: delete_key

Delete specified field or key



217
218
219
220
221
222
223
# File 'lib/sd_struct/base.rb', line 217

def delete_field(name)
  sym = name.to_sym
  @table.delete(sym) do
    raise NameError.new("no field `#{sym}' in #{self}", sym)
  end
  singleton_class.__send__(:remove_method, sym, "#{sym}=")
end

#dig(*args) ⇒ SDStruct, ...

Dig the content of @table which is a hash

Parameters:

  • multiple (Symbol)

    symbols

Returns:

  • (SDStruct, Hash, Array, String, Integer, Float, Boolean, nil)

    first matched result



68
69
70
# File 'lib/sd_struct/deep_search.rb', line 68

def dig(*args)
  @table.dig(*args)
end

#dig_deep(*args) ⇒ SDStruct, ...

Dig deep into Hash until non-Array and non-Hash primitive data is found

Parameters:

  • multiple (Symbol)

    symbols

Returns:

  • (SDStruct, Hash, Array, String, Integer, Float, Boolean, nil)

    first matched result



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

def dig_deep(*args)
  full_args = args.dup
  parent_key = args.shift
  result = dig(parent_key)
  unless result.nil? || args.length.zero?
    if result.respond_to?(:dig)
      result = result.dig(*args)
    end
  end
  if result.nil?
    @table.values
          .select{|v| v.respond_to?(:dig) }
          .each do |v|
            if v.respond_to?(:dig_deep) || v.is_a?(Array)
              result = v.dig_deep(*full_args)
            end
            return result unless result.nil?
          end
  end
  return result
end

#each_pairObject

Yields all attributes (as a symbol) along with the corresponding values or returns an enumerator if not block is given. Example:

require 'sd_struct'
data = SDStruct.new("name" => "Matz", "coding language" => :ruby)
data.each_pair.to_a  # => [[:name, "Matz"], ["coding language", :ruby]]


86
87
88
89
# File 'lib/sd_struct/base.rb', line 86

def each_pair
  return to_enum(__method__) { @table.size } unless block_given?
  @table.each_pair{|p| yield p}
end

#eql?(other) ⇒ Boolean

Compares this object and other for equality. An SDStruct is eql? to other when other is an SDStruct and the two objects’ Hash tables are eql?.

Returns:

  • (Boolean)


178
179
180
181
# File 'lib/sd_struct/base.rb', line 178

def eql?(other)
  return false unless other.kind_of?(self.class)
  @table.eql?(other.table)
end

#find(key_str, opts = {}) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/sd_struct/deep_search.rb', line 72

def find(key_str, opts = {})
  opts = {
    separator: "/"
  }.merge(opts)

  sep = Regexp.quote(opts[:separator])

  args = begin
    key_str.gsub(/^#{sep}(?!#{sep})|#{sep}+$/, '')
           .split(/#{sep}{2,}/)
           .map do |ks|
             ks.split(/#{sep}/)
               .map do |x|
                 x.strip!
                 if !!x[/\A[-+]?\d+\z/]
                   x.to_i
                 else
                   if x[/^$|\s+/]
                     x
                   else
                     x.underscore.to_sym
                   end
                 end
               end
           end
  end

  if !(parent_key = args.shift) # args == [], key_str == ""
    return
  else # e.g. args == [[], ..] or [[.., ..], [..]]
    result = dig(*parent_key) unless parent_key.empty?

    unless args.length.zero?
      args.each do |a|
        result = result.dig_deep(*a) rescue result = dig_deep(*a)
      end
    end
  end
  return result
end

#hashObject

Compute a hash-code for this SDStruct. Two hashes with the same content will have the same hash code (and will be eql?).



188
189
190
# File 'lib/sd_struct/base.rb', line 188

def hash
  @table.hash
end

#initialize_copy(orig) ⇒ Object

Duplicate an SDStruct object members.



58
59
60
61
# File 'lib/sd_struct/base.rb', line 58

def initialize_copy(orig)
  super
  @table = @table.dup
end

#inspectObject Also known as: to_s

Returns a string containing a detailed summary of the keys and values.



142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/sd_struct/base.rb', line 142

def inspect
  str = "#<#{self.class}"

  ids = (Thread.current[InspectKey] ||= [])
  if ids.include?(object_id)
    return str << ' ...>'
  end

  ids << object_id
  begin
    first = true
    for k,v in @table
      str << "," unless first
      first = false
      str << " #{k[/\s+/] ? "['#{k}']" : ".#{k}"}=#{v.inspect}"
    end
    return str << '>'
  ensure
    ids.pop
  end
end

#keysObject

Expose all keys



210
211
212
# File 'lib/sd_struct/base.rb', line 210

def keys
  @table.keys
end

#marshal_dumpObject

Provides marshalling support for use by the Marshal library.



66
67
68
# File 'lib/sd_struct/base.rb', line 66

def marshal_dump
  to_h
end

#marshal_load(x) ⇒ Object

Provides marshalling support for use by the Marshal library.



73
74
75
# File 'lib/sd_struct/base.rb', line 73

def marshal_load(x)
  @table = x.map{|a| structurize(a) }.original_to_h
end

#non_spaced_keysObject Also known as: fields

Expose keys without space(s)



202
203
204
# File 'lib/sd_struct/base.rb', line 202

def non_spaced_keys
  methods(false).select{|x| x[/^\S+[^=]$/]}
end

#spaced_keysObject

Expose keys with space(s)



195
196
197
# File 'lib/sd_struct/base.rb', line 195

def spaced_keys
  @table.keys - non_spaced_keys
end

#to_h(opts = {}) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/sd_struct/deep_convert.rb', line 12

def to_h(opts = {})
  opts = {
    camelize_keys: false,
    exclude_blank_values: false,
    values_to_exclude: []
  }.merge(opts)

  @table.map do |k, v|
    v = v.to_h(opts) if v.is_a?(self.class) || v.is_a?(Array)
    k = k.to_s.camelize(:lower) if opts[:camelize_keys] && !k[/\s+/]
    [k, v]
  end.original_to_h
     .select{|_,v| opts[:exclude_blank_values] ? v.present? : !v.nil? }
     .select{|_,v| !v.in?(opts[:values_to_exclude]) }
end

#to_json(opts = {}) ⇒ Object



28
29
30
31
32
33
34
35
36
# File 'lib/sd_struct/deep_convert.rb', line 28

def to_json(opts = {})
  opts = {
    camelize_keys: true,
    exclude_blank_values: true,
    values_to_exclude: [0, [""], [{}]]
  }.merge(opts)

  to_h(opts).to_json
end