Skip to content

Instantly share code, notes, and snippets.

@tihuan
Last active August 29, 2015 14:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tihuan/a72c7c5c7e1ebf4a57a0 to your computer and use it in GitHub Desktop.
Save tihuan/a72c7c5c7e1ebf4a57a0 to your computer and use it in GitHub Desktop.
  1. We use a third party gem stock_quote to pull real time data. But currently it's being called directly in StocksController#update_stocks. How would you improve the code and make the controller skinnier? Hint: Services

  2. StocksController#update_stocks is only used by StocksController internally, so where would you move the method to?

require 'stock_quote'
require 'pp'
class StocksController < ApplicationController
before_action :load_user
skip_before_filter :verify_authenticity_token
def index
update_stocks
end
def update_stocks
@stock_symbols.each do |symbol|
@stocks << StockQuote::Stock.quote(symbol, nil, nil,
[ "Symbol",
"Name",
"LastTradePriceOnly"
] )
end
end
def add
stock = Stock.new(user_id: @user.id, symbol: params["symbol"])
respond_to do |format|
if stock.save
format.js { render json: stock }
else
puts "you failed"
end
end
end
def destroy
stock = Stock.find_by(user_id: @user.id, symbol: params["symbol"])
respond_to do |format|
if stock.destroy
format.js { render json: stock }
end
end
end
def endpoint
update_stocks
render json: @stocks
end
private
def load_user
@user = current_user
@stocks = []
@stock_symbols = []
@user.stocks.each do |stock|
@stock_symbols << stock.symbol
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment