Skip to content

Instantly share code, notes, and snippets.

@sunloverz
Created April 30, 2019 13:58
Show Gist options
  • Save sunloverz/c31e54591c80d9dd24bdf013e2892cf6 to your computer and use it in GitHub Desktop.
Save sunloverz/c31e54591c80d9dd24bdf013e2892cf6 to your computer and use it in GitHub Desktop.
Ruby open class refactoring
class ActiveRecord::Base
def self.has_statuses(*status_names)
validates :status,
:presence => true,
:inclusion => { :in => status_names }
# Status Finders
status_names.each do |status_name|
scope "all_#{status_name}", where(:status => status_name)
end
# Status Accessors
status_names.each do |status_name|
define_method "#{status_name}?" do
status == status_name
end
end
end
end
class Purchase < ActiveRecord::Base
has_statuses :in_progress, :submitted, :approved, :shipped,
:received
end
class Purchase < ActiveRecord::Base
STATUSES = %w(in_progress submitted approved shipped received)
validates_presence_of :status
validates_inclusion_of :status, :in => STATUSES
# Status Finders
class << self
STATUSES.each do |status_name|
define_method "all_#{status_name}"
where(:status => status_name)
end
end
# Status Accessors
STATUSES.each do |status_name|
define_method "#{status_name}?"
status == status_name
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment