Skip to content

Instantly share code, notes, and snippets.

@pdbradley
Created March 4, 2018 01:07
Show Gist options
  • Save pdbradley/e73080e3475446c13d6dffd4409427fa to your computer and use it in GitHub Desktop.
Save pdbradley/e73080e3475446c13d6dffd4409427fa to your computer and use it in GitHub Desktop.
jeremiah presenter
products = Product.by_company(current_user.company.slug).includes(:facilities, :total_stocks).distinct(:sku)
sql = "SELECT DISTINCT ON (product_id) * FROM facility_stocks WHERE product_id IN (#{@products.pluck(:id).join(', ')}) ORDER BY product_id, created_at DESC"
facility_stocks = ActiveRecord::Base.connection.execute(sql)
facilities = Facility.all # or whatever conditions you are putting on that
# then construct a collection of stuff you want to show in the view.
# Basic principle: don't calculate anything in a view unless absolutely necessary
# "separation of concerns" helps you know where to look for your logic
# strictly speaking the controller is not the best place for this stuff here (it would be better
# in a presenter class) but this is a step in the right direction
#
# Define a temporary container for the complex data using Struct
FacilityInfo = Struct.new(:facility, :pallet_quantity, :case_quantity, :item_quantity)
@facility_collection_for_view = facilities.map do |facility|
pallet_quantity = facility_stocks.select { |h| h['facility_id' ] == facility.id}.map { |h| h['pallet_quantity'] }.sum
case_quantity = facility_stocks.select { |h| h['facility_id' ] == facility.id}.map { |h| h['case_quantity'] }.sum
item_quantity = facility_stocks.select { |h| h['facility_id' ] == facility.id}.map { |h| h['item_quantity'] }.sum
FacilityInfo.new(facility: facility, pallet_quantity: pallet_quantity, case_quantity: case_quantity, item_quantity: item_quantity)
end
#in view
<% @facility_collection_for_view.each do |facility_info| %>
<td><%= facility_info.pallet_quantity %></td>
<td><%= facility_info.case_quantity %></td>
<td><%= facility_info.item_quantity %></td>
<% end %>
# anyway, now at least when you need to reason about your data, you can do it in the ruby code and not in
# the html or erb.
#
# Basically what you want to build is a "presenter" class whenever you have a bunch of data
# that needs all kinds of massaging to get to what you want to show. You can build a class
# that just has ONE job--to get at that data and build a presenter object that can be passed to a view
# http://nithinbekal.com/posts/rails-presenters/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment