Skip to content

Commit

Permalink
Merge pull request #12 from dreyks/fix-deep-camelcase
Browse files Browse the repository at this point in the history
fix nested snake-casing
  • Loading branch information
vergilet authored May 2, 2024
2 parents c72b387 + 73aaf1e commit 576015f
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 18 deletions.
7 changes: 4 additions & 3 deletions lib/monobank/methods/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,11 @@ def initialize(auth: nil)
end

def call
attributes = response
return define_resources(attributes) if attributes.code == 200
http_response = response
attributes = http_response.parsed_response
return define_resources(attributes) if http_response.code == 200

Monobank::Resources::Error.new(attributes.merge('code' => attributes.code))
Monobank::Resources::Error.new(attributes.merge('code' => http_response.code))
end

private
Expand Down
27 changes: 12 additions & 15 deletions lib/monobank/resources/base.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,27 +8,24 @@ def self.define_fields(attributes)
end

def initialize(attributes)
@attributes = {}
snake_case_attributes = deep_snake_case(attributes)
snake_case_attributes.each { |key, value| @attributes[method_name(key)] = value }
@attributes = deep_snake_case(attributes)
end

def method_name(key)
key.gsub(/(.)([A-Z])/,'\1_\2').downcase
end

def deep_snake_case(hash)
return hash unless hash.is_a?(Array) || hash.is_a?(Hash)

hash.each_with_object({}) do |(key, value), object|
object[method_name(key)] =
if value.is_a? Hash
deep_snake_case(value)
elsif value.is_a? Array
value.map { |element| deep_snake_case(element) }
else
value
end
def deep_snake_case(object)
if object.is_a?(Hash)
object.map do |key, value|
[method_name(key), deep_snake_case(value)]
end.to_h
elsif object.is_a?(Array)
object.map do |value|
deep_snake_case(value)
end
else
object
end
end

Expand Down
8 changes: 8 additions & 0 deletions spec/monobank_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,14 @@
result = Monobank.client_info(token:)
expect(result.name).to eq 'Мазепа Іван'
expect(result.accounts.length).to eq 1
expect(result.accounts.first.currency_code).to eq 980
expect(result.attributes).to match hash_including(
'accounts' => array_including([
hash_including(
"currency_code" => 980
)
])
)
end
end

Expand Down

0 comments on commit 576015f

Please sign in to comment.