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

VERSION =
"0.1.1"

Instance Method Summary collapse

Constructor Details

#initialize(hash = nil, opts = {}) ⇒ 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">


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

def initialize(hash = nil, opts = {})
  opts = {
    deep:           true,
    symbolize_keys: true
  }.merge(opts)

  @deep = opts[:deep]
  @table = {}
  if hash
    hash.each_pair do |k, v|
      @table[naturalize(k)] = structurize(v) # @deep is used in this method
    end
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(m_id, *args) ⇒ Object



235
236
237
238
239
240
241
242
243
244
245
246
# File 'lib/sd_struct/base.rb', line 235

def method_missing(m_id, *args)
  m_nat = naturalize(m_id)
  if args.length.zero?
    if @table.key?(m_nat)
      @table[new_struct_member(m_nat)]
    end
  else
    err = NoMethodError.new "undefined method `#{m_id}' for #{self}", m_id, args
    err.set_backtrace caller(1)
    raise err
  end
end

Instance Method Details

#==(other) ⇒ Object



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

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


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

def [](name)
  @table[name] || @table[naturalize(name)]
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


141
142
143
144
145
146
# File 'lib/sd_struct/base.rb', line 141

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(naturalize(name))] = structurize(value)
end

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

Deletes specified field or key



226
227
228
229
230
231
232
# File 'lib/sd_struct/base.rb', line 226

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

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

Digs 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, ...

Digs 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]]


90
91
92
93
# File 'lib/sd_struct/base.rb', line 90

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)


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

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

#find(key_str, opts = {}) ⇒ SDStruct, ...

Finds value with keys specified like xpath

Parameters:

  • key (String)

    string

  • option (Hash)

    Hash

Returns:

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

    first matched result



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
112
113
114
115
116
117
118
# File 'lib/sd_struct/deep_search.rb', line 79

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[/^$|^[A-Z]|\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

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



197
198
199
# File 'lib/sd_struct/base.rb', line 197

def hash
  @table.hash
end

#initialize_copy(orig) ⇒ Object

Duplicates an SDStruct object members.



62
63
64
65
# File 'lib/sd_struct/base.rb', line 62

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.



151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# File 'lib/sd_struct/base.rb', line 151

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

  ids = (Thread.current[:sd_struct] ||= [])
  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

Exposes all keys



219
220
221
# File 'lib/sd_struct/base.rb', line 219

def keys
  @table.keys
end

#marshal_dumpObject

Provides marshalling support for use by the Marshal library.



70
71
72
# File 'lib/sd_struct/base.rb', line 70

def marshal_dump
  to_h
end

#marshal_load(x) ⇒ Object

Provides marshalling support for use by the Marshal library.



77
78
79
# File 'lib/sd_struct/base.rb', line 77

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

#non_spaced_keysObject Also known as: fields

Exposes keys without space(s)



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

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

#spaced_keysObject

Exposes keys with space(s)



204
205
206
# File 'lib/sd_struct/base.rb', line 204

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