-
-
Save kpearson/5fbe20539edb13a1c9cc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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