Class: Bunny::Object

Inherits:
OpenStruct
  • Object
show all
Defined in:
lib/bunny/object.rb

Instance Method Summary collapse

Constructor Details

#initialize(attributes) ⇒ Object

Returns a new instance of Object.



5
6
7
# File 'lib/bunny/object.rb', line 5

def initialize(attributes)
  super to_ostruct(attributes)
end

Instance Method Details

#camel_to_snake(input) ⇒ Object



19
20
21
22
23
24
# File 'lib/bunny/object.rb', line 19

def camel_to_snake(input)
  str = input.is_a?(Symbol) ? input.to_s : input
  snake_case_str = str.gsub(/([A-Z])/, '_\1').downcase
  snake_case_str.sub!(/^_/, "")
  input.is_a?(Symbol) ? snake_case_str.to_sym : snake_case_str
end

#to_ostruct(obj) ⇒ Object



9
10
11
12
13
14
15
16
17
# File 'lib/bunny/object.rb', line 9

def to_ostruct(obj)
  if obj.is_a?(Hash)
    OpenStruct.new(obj.map { |key, val| [ camel_to_snake(key), to_ostruct(val) ] }.to_h)
  elsif obj.is_a?(Array)
    obj.map { |o| to_ostruct(o) }
  else # Assumed to be a primitive value
    obj
  end
end