Module: MailyHerald::Autonaming

Included in:
List, Mailing, Sequence
Defined in:
lib/maily_herald/autonaming.rb

Overview

Provides some common patters for models that have both :name and :title attributes. It adds some format constraints to :name and title attributes and makes sure that they are always both set properly.

If only :name is provided, it will be used also as a:title. If only :title is provided, :name will be automatically generated out of it.

Defined Under Namespace

Modules: ClassMethods, InstanceMethods

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object


11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/maily_herald/autonaming.rb', line 11

def self.included(base)
  base.extend ClassMethods
  base.send :include, MailyHerald::Autonaming::InstanceMethods

  base.class_eval do
    validates   :name,                presence: true, format: {with: /\A\w+\z/}, uniqueness: true
    validates   :title,               presence: true

    before_validation do
      if self.title && !self.name
        self.name = self.title.parameterize.underscore
      elsif self.name && !self.title
        self.title = self.name
      end
    end
  end
end