Skip to content

Instantly share code, notes, and snippets.

@kpearson
Forked from JoshCheek/whatevz.rb
Last active August 29, 2015 14:19
Show Gist options
  • Save kpearson/5fbe20539edb13a1c9cc to your computer and use it in GitHub Desktop.
Save kpearson/5fbe20539edb13a1c9cc to your computer and use it in GitHub Desktop.
require 'active_record'
ActiveRecord::Base.establish_connection adapter: 'sqlite3', database: ':memory:'
ActiveRecord::Schema.define do
self.verbose = false
create_table :businesses do |t|
t.string :name
end
create_table :orders do |t|
t.string :name
t.integer :business_id
t.integer :status_id
end
end
class Business < ActiveRecord::Base
has_many :orders
end
class Order < ActiveRecord::Base
belongs_to :business
scope :ordered, -> { where status_id: 1 }
scope :cancelled, -> { where status_id: 2 }
end
Business.create! name: 'Turing' do |b|
b.orders.build name: 'books', status_id: 1
b.orders.build name: 'computers', status_id: 2
b.orders.build name: 'tables', status_id: 1
b.orders.build name: 'chairs', status_id: 3
end
class OrdersPresenter
def initialize(all_orders)
@all_orders = all_orders
end
def ordered
@all_orders.where(status_id: 1)
end
def ordered_names
ordered.map(&:name)
end
def cancelled
@all_orders.where(status_id: 2)
end
end
# setup
business = Business.first
# no abstractions
orders = business.orders
orders.where(status_id: 1).map(&:name)
orders.where(status_id: 2).map(&:name)
# presenter solution
orders = OrdersPresenter.new(business.orders)
orders.ordered_names
orders.cancelled.map(&:name)
# scope solution
orders = business.orders
orders.ordered.map(&:name)
orders.cancelled.map(&:name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment