Skip to content

Instantly share code, notes, and snippets.

@stephenrichards
Created December 12, 2018 09:02
Show Gist options
  • Save stephenrichards/07b764f6a749f4a702e52e000ddd2f80 to your computer and use it in GitHub Desktop.
Save stephenrichards/07b764f6a749f4a702e52e000ddd2f80 to your computer and use it in GitHub Desktop.
class OysterCardsController < ApplicationController
def index
@cards = OysterCard.order(balance: :desc)
end
def show
end
def swipe_out
@card = OysteCard.find(params[:id])
authorize @card # uses a Pundit policy to determine whether or not the current user is authorised to update this card
@journey_end_station = Station.find(params[:swipe_out][journey_end_station_id])
if @card.journey_start_station.nil?
flash[:alert] << "No start of journey recorded - you have been charged the maximum fare"
@card.balance -= MAXIMUM_FARE
else
if @card.loaded_with_season_ticket?
@fare = calculate_fare_with_season_ticket
else
@fare = calculate_fare
end
end
if @fare > 0
@card.balance -= @fare
@card.record_transaction(@fare, @journey_end_station)
end
if @card.balance < 0
flash[:alert] << 'You have no balance on your card - you must top up before travelling again'
end
end
private
def calculate_fare_with_season_ticket
# all sorts of code to determine whether the season ticket covers the journey
# or whether there is a fare to pay
end
def calculate_fare
# work out fare
zones_travelled = [@card.start_journey_station.zone, journey_end_station.zone].sort
fare = FARES[zones_travelled]
@card.balance -= fare
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment