Skip to content

Instantly share code, notes, and snippets.

@zeljkokalezic
Last active July 25, 2017 13:54
Show Gist options
  • Save zeljkokalezic/680d113fd4092b37e0408d5a186b8627 to your computer and use it in GitHub Desktop.
Save zeljkokalezic/680d113fd4092b37e0408d5a186b8627 to your computer and use it in GitHub Desktop.
DRY Rails model using enums
#Extended from https://gist.github.com/harssh-sparkway/8707634
#Take I - Naive
class Article < ActiveRecord::Base
def self.all_published
where("state = ?", "published")
end
def self.all_draft
where("state = ?", "draft")
end
def self.all_spam
where("state = ?", "spam")
end
def published?
self.state == 'published'
end
def draft?
self.state == 'draft'
end
def spam?
self.state == 'spam'
end
end
#Take II - better but maybe unreadable to novices
class Article < ActiveRecord::Base
STATES = ['draft', 'published', 'spam']
class <<self
STATES.each do |state_name|
define_method "all_#{state_name}" do
where("state = ?", state_name)
end
end
end
STATES.each do |state_name|
define_method "#{state_name}?" do
self.state == state_name
end
end
end
#Take III - DRYed completely using enums http://api.rubyonrails.org/classes/ActiveRecord/Enum.html
class Article < ActiveRecord::Base
enum state: [:draft, :published, :spam]
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment