Skip to content

Instantly share code, notes, and snippets.

@diogobaeder
Created February 7, 2013 06:13
Show Gist options
  • Save diogobaeder/4728921 to your computer and use it in GitHub Desktop.
Save diogobaeder/4728921 to your computer and use it in GitHub Desktop.
Refactor the big monster into pieces
def create_order(products, user):
connection = db_connection()
connection.begin_transaction()
try:
process_order(connection, products, user)
except Exception as e:
connection.rollback()
message = 'Order failed : %s' % e
else:
connection.commit()
message = 'Order successful!'
finally:
connection.close()
send_email(user, message)
def process_order(connection, products, user):
amount = calculate_amount(products)
order = new_order(connection, amount, user)
add_items(connection, order)
create_payment(connection, amount, user)
def calculate_amount(products):
amount = Decimal('0')
for product in products:
amount += product.price
return amount
def new_order(connection, amount, user):
order_repository = order_repository_for(connection)
order = order_repository.create()
order.amount = amount
order.user = user
order.date = today()
return order
def add_items(connection, order):
item_repository = item_repository_for(connection)
for product in products:
item = item_repository.create()
item.name = product.name
item.price = product.price
item.date = today()
item.order = order
item_repository.add(item)
def create_payment(connection, amount, user):
payment_repository = payment_repository_for(connection)
payment = payment_repository.create()
payment.amount = amount
payment.user = user
authorized = authorize(payment)
payment.transaction_id = authorized.transaction_id
payment_repository.add(payment)
def authorize(payment):
authorized = payment_gateway.authorize(payment)
if not authorized:
raise Exception('You cannot buy that!')
return authorized
def send_email(user, message):
mail = mailer.create_message()
mail.to = user.email
mail.from_ = 'The store'
mail.message = message
mail.send()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment