Skip to content

Instantly share code, notes, and snippets.

@dwyn

dwyn/cafe_ideas.md

Last active Oct 6, 2020
Embed
What would you like to do?

You could have a few options. The possiblities are (as usual) endless with Ruby.

Option 1

This is something I whipped up really quickly. I dont love it, but I think it works. app/models/cafe.rb

scope :open_cafes, -> {
  today = Date.today.strftime("%A").downcase
  joins(:openings).where("day = ? AND status = 'open'", today) 
}

At the end of the day, ActiveRecord scope methods are just class methods that leverage methods specific to ActiveRecord. So if I were to rewrite the method from above, it would look something like:

def self.open_cafes
  today = Date.today.strftime("%A").downcase
  joins(:openings).where("day = ? AND status = 'open'", today) 
end

Option 2

Option 2 comes in two parts. First part is in your scope method in the Cafe model. app/models/cafe.rb

scope :open_cafes, -> (wday) { joins(:openings).where("day = ? AND status = 'open'", wday) }

app/controllers/application_controller.rb Then, in your application controller you could do something like

class ApplicationController < ActionController::Base
  #gives access to the methods in views
  helper_method :user_is_authenticated, :current_user, :today

  def home
  end

  private
  def today
    return Date.today.strftime("%A").downcase
  end

  def user_is_authenticated
    !!current_user
  end

  def current_user
    User.find_by(id: session[:user_id])
  end
end

Afterwards, you should be free to call Cafe.open_cafes(today) in your controller.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment