Created
January 26, 2022 02:50
-
-
Save johndavid400/0b5b466d59a419c81ba122bb94d033c6 to your computer and use it in GitHub Desktop.
what I used before finding enum in Rails
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
# This module contains creates getter, setter, and scopes for each provided status. | |
# You must have a 'status:string' column on whatever table you are including this module on. | |
# | |
# Use in any model: | |
# include Status | |
# | |
# Then you must add a list of status names you wish to use for the model. | |
# statuses :open, :closed, :archived | |
# | |
# Including the module and a list of statuses (ie. 'open') will do the following: | |
# 1. create a getter method: | |
# @resource.open? # returns true if status == "open", false if not. | |
# 2. create a setter method: | |
# @resource.open! # sets the status of the resource to 'open' and saves (if changed). | |
# 3. create class method (to return all objects with status equal to the class method name): | |
# Resource.open # returns an ActiveRecord collection of Resources where status == 'open' | |
require 'active_support/concern' | |
module Status | |
extend ActiveSupport::Concern | |
def set_status!(str) | |
self.status = str | |
save if changed? | |
end | |
class_methods do | |
def statuses(*args) | |
scope :status_names, -> { args } | |
args.each do |arg| | |
# Create a scope that returns records with a status equal to the name of the scope | |
scope arg, -> { where(status: arg.to_s) } | |
# Create a method that checks if the status of a record is equal to the name of the method | |
define_method [arg.to_s, '?'].join.to_sym do | |
status == arg.to_s | |
end | |
# Create a method that sets the status of a record equal to the name of the method | |
define_method [arg.to_s, '!'].join.to_sym do | |
set_status!(arg) | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment