creddit/app/models/subcreddit.rb
Andrew Tomaka d3dd0ff848 Add the subcreddit MVC
Notes on closing subcreddit:

This doesn't seem great.  Would be slightly better if closed could be referenced
as true or false instead of '0' or '1' in the model.  Testing this is a bit
messy, but Tiemcop makes it a bit better.

Notes on subcreddit validations:

This is still not ideal.  For starters, from
http://guides.rubyonrails.org/active_record_validations.html:

"Note that some databases are configured to perform case-insensitive searches
anyway."

It also seems difficult to validate fields that are set in before_save since
validations occur before callbacks.  Revisit this (perhaps friendly_id wll save
us).
2015-07-13 17:01:12 -04:00

53 lines
967 B
Ruby

RESERVED_SLUGS = %w(new edit)
class Subcreddit < ActiveRecord::Base
belongs_to :owner, class_name: 'User'
attr_accessor :closed
before_save :set_slug
before_save :set_closed_at
validates :name,
presence: true,
format: /\A(?! )[a-z0-9 ]*(?<! )\z/i,
uniqueness: { case_sensitive: false },
length: { minimum: 3, maximum: 21 }
validate :slug_is_not_a_route
validates :closed,
format: /\A[01]?\z/
def to_param
self.slug
end
def closed?
self.closed_at != nil
end
private
def set_slug
self.slug = sluggify_name
end
def sluggify_name
self.name.downcase.tr(' ', '_')
end
def set_closed_at
if closed == '1' && closed_at == nil
self.closed_at = Time.now
elsif closed == '0' && closed_at != nil
self.closed_at = nil
end
end
def slug_is_not_a_route
if RESERVED_SLUGS.include?(sluggify_name)
errors.add(:name, 'cannot be a reserved keyword')
end
end
end