Skip to content

Instantly share code, notes, and snippets.

@dwyn
Last active October 6, 2020 20:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dwyn/55c021dc949f571fcce7ba7e8c41889f to your computer and use it in GitHub Desktop.
Save dwyn/55c021dc949f571fcce7ba7e8c41889f to your computer and use it in GitHub Desktop.

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