Class: Motion::OpenStruct

Inherits:
BasicObject
Defined in:
lib/motion-ostruct/version.rb,
lib/motion-ostruct/open_struct.rb

Constant Summary collapse

VERSION =
'0.0.1'

Instance Method Summary collapse

Constructor Details

#initialize(hash) ⇒ OpenStruct

Returns a new instance of OpenStruct.



4
5
6
7
# File 'lib/motion-ostruct/open_struct.rb', line 4

def initialize(hash)
  @struct = ::Struct.new(*hash.keys.map { |k| k.to_sym })
  @struct = @struct.new(*hash.values)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, &block) ⇒ Object



13
14
15
16
17
18
19
20
21
22
# File 'lib/motion-ostruct/open_struct.rb', line 13

def method_missing(method_name, *args, &block)
  if method_name.to_s.index('=') && !@struct.respond_to?(method_name)
    vals = @struct.to_h.values
    getter_name = method_name.to_s.gsub('=', '')
    getters = ((@struct.to_h.keys.map { |k| k.to_sym }) + [getter_name.to_sym])
    @struct = ::Struct.new(*getters)
    @struct = @struct.new(*vals)
  end
  @struct.send(method_name, *args, &block)
end

Instance Method Details

#==(other) ⇒ Object



9
10
11
# File 'lib/motion-ostruct/open_struct.rb', line 9

def ==(other)
  to_h == other.to_h
end

#respond_to_missing?(method_name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


24
25
26
27
# File 'lib/motion-ostruct/open_struct.rb', line 24

def respond_to_missing?(method_name, include_private = false)
  return true if @struct.respond_to?(method_name)
  return true if super
end