Skip to content

Commit

Permalink
Add feature to list peeps in reverse date order
Browse files Browse the repository at this point in the history
  • Loading branch information
marshallwj committed Apr 1, 2022
1 parent ea56f75 commit 2ab76b6
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
2 changes: 1 addition & 1 deletion app.rb
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ class Chitter < Sinatra::Base
end

get "/peeps" do
@peeps = Peep.all
@peeps = Peep.sort_by_date
erb(:"peeps/index")
end

Expand Down
15 changes: 14 additions & 1 deletion lib/peep.rb
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ def self.create(message:, date: Date.today.to_s)
connection = PG.connect(dbname: "chitter")
end
result = connection.exec_params(
"INSERT into peeps (message, date) VALUES ($1, $2) RETURNING id, message, date",
"INSERT INTO peeps (message, date) VALUES ($1, $2) RETURNING id, message, date",
[message, date]
)
Peep.new(id: result[0]["id"], message: result[0]["message"], date: result[0]["date"])
Expand All @@ -33,4 +33,17 @@ def self.all
Peep.new(id: peep["id"], message: peep["message"], date: peep["date"])
end
end

def self.sort_by_date
if ENV["RACK_ENV"] == "test"
connection = PG.connect(dbname: "chitter_test")
else
connection = PG.connect(dbname: "chitter")
end
result = connection.exec("SELECT * FROM peeps ORDER BY date DESC")
result.map do |peep|
Peep.new(id: peep["id"], message: peep["message"], date: peep["date"])
end
end

end
12 changes: 12 additions & 0 deletions spec/peep_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,16 @@
expect(peeps.first.date).to eq(Date.today.to_s)
end
end

describe "::sort_by_date" do
it "sorts peeps in reverse chronological order" do
first_peep = Peep.create(message: "Test peep 1", date: "2020-01-01")
second_peep = Peep.create(message: "Test peep 2", date: "2022-01-01")
third_peep = Peep.create(message: "Test peep 3", date: "2021-01-01")
sorted_peeps = Peep.sort_by_date
expect(sorted_peeps[0].id).to eq(second_peep.id)
expect(sorted_peeps[1].id).to eq(third_peep.id)
expect(sorted_peeps[2].id).to eq(first_peep.id)
end
end
end

0 comments on commit 2ab76b6

Please sign in to comment.