Skip to content

Commit

Permalink
refactor: simplify GetWeatherData service object
Browse files Browse the repository at this point in the history
  • Loading branch information
ianbayne committed May 12, 2024
1 parent 0498a95 commit 00c8ee3
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 20 deletions.
32 changes: 16 additions & 16 deletions app/services/get_weather_data.rb
Original file line number Diff line number Diff line change
@@ -1,25 +1,25 @@
class GetWeatherData
include Callable

def initialize(city)
def initialize(city, client = Clients::OpenWeatherMap)
@city = city
@client = client
end

def call
@result = Clients::OpenWeatherMap.call(@city)
OpenStruct.new(
success?: success?,
payload: @result[:payload],
error: @result[:error],
error_status_code: error_status_code
)
end

def success?
@result[:error].nil?
end

def error_status_code
@result[:error_status_code]
result = @client.call(@city)

if result[:error].nil?
OpenStruct.new(
success?: true,
payload: result[:payload],
)
else
OpenStruct.new(
success?: false,
error: result[:error],
error_status_code: result[:error_status_code]
)
end
end
end
11 changes: 7 additions & 4 deletions spec/requests/api/v1/weather_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,18 @@
expect(data["wind_speed"]).to be_kind_of(Float)
end

it "returns a failure message on fail" do
allow_any_instance_of(GetWeatherData).to receive(:success?).and_return(false)
allow_any_instance_of(GetWeatherData).to receive(:error_status_code).and_return('500')
it "returns a failure message and status code on fail" do
allow_any_instance_of(Clients::OpenWeatherMap).to receive(:call)
.and_return(OpenStruct.new(
error: 'example error',
error_status_code: 500
))

city = "Tokyo"
get "/api/v1/weather/#{city}"

expect(response).to have_http_status(:internal_server_error)
expect(response.parsed_body["message"]).to match(/Something went wrong/)
expect(response.parsed_body["message"]).to match(/Something went wrong: example error/)
end
end
end

0 comments on commit 00c8ee3

Please sign in to comment.