Skip to content

Instantly share code, notes, and snippets.

@kchens
Last active August 29, 2015 14:17
Show Gist options
  • Save kchens/c3e5b1497c71a31a776a to your computer and use it in GitHub Desktop.
Save kchens/c3e5b1497c71a31a776a to your computer and use it in GitHub Desktop.
"Skinny" StockController
# ######################
# Refactored
# ######################
# app/controllers/stocks_controller.rb
require 'stock_quote'
require 'pp'
class StocksController < ApplicationController
before_action :load_stock_service, :load_user_stock_symbols
skip_before_filter :verify_authenticity_token
# added :html because the #index action doesn't specify JSON. Client may want a different
# format like HTML.
respond_to :json, :html
def index
load_updated_stocks
# As we are in the index action of the Stocks Controller, it looks like we want to return
# all the stocks, not just stock symbols. So, we can use respond_with to return the correct
# format -- based on the MIME-type requested by the client. We pass in the stocks.
respond_with @stock_service.stocks
end
def add
stock = Stock.new(user_id: @user.id, symbol: params["symbol"])
if stock.save
render json: stock
else
puts "you failed"
end
end
def destroy
stock = Stock.find_by(user_id: @user.id, symbol: params["symbol"])
if stock.destroy
render json: stock
end
end
def endpoint
load_updated_stocks
render json: @stock_service.stocks
end
private
# Change update_stocks-related methods to a private method because
# (1) it is used internally by the controller,
# (2) we don't want the user to access this method, and
# (3) we want to make our controller code clearer -- show that this method is not accessible by any routes
def load_stock_service(user = current_user)
@stock_service = StockService.new(user)
end
def load_user_stock_symbols
@stock_service.get_user_stock_symbols
end
def load_updated_stocks
@stock_service.update_stocks
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment