Нистратов Артём
anistratov@go-promo.ru
Validations
validates :email,presence: true uniqunesses: true acceptance: true acceptance: { accept: 'yes' } confirmation: true format: {
with: EMAIL_REGEX
} message: "Невалидный Email"
}{ scope: :name }length: { in: 5..200 }length: { minimum: 10, maximum: 200, too_long: '%{count} too long', too_short: '%{count} too short'
} tokenizer: lambda { |str|
str.split(/\s+/)
},numericality: truenumericality: { only_integer: true,
greater_than: 10, greater_than_or_equal_to: 10, equal_to: 15, less_than: 100, less_than_or_equal_to: 100, odd: true, even: true
}validates :nickname, allow_nill: trueallow_blank: truevalidates :rules,
acceptance: true,
on: :create on: [:create, :publish]record.valid? :publishProc.new do |*args|
...
endproc { |*args| ... }lambda { |*args| ... }-> (*args) { ... }Proc
validates :content,
if: :content_changed?validates :title, presence: true,
if: -> (snippet) { snippet.public? }validates :first_name, :last_name,
presence: true,
unless: "nickname.present?"validate :langs_countdef langs_count
if langs.count > 3
errors.add :langs,
'Указано слишком много языков'
end
endValidators
class ContentChecks < ActiveModel::Validator
def validate(record)
...
record.errors.add :content, 'Все плохо'
...
end
endvalidate_with ContentChecksCallbacks
before_create do
...
endbefore_save :recalculate_dates,
if: :event_at_changed?
def recalculate_dates
...
endafter_validation :check_permissions,
if: -> (record) { ... }after_commit :send_message,
on: :createsave context: :publisharound_save do
...
yield
...
endhas_many :snippets,
after_add: :update_statistic,
after_remove: :update_statisticafter_initialize :set_defautlsafter_touch :logbelongs_to :user, touch: trueclass AuditCallbacks
def before_save
# log :changes
end
def after_destroy
# log delete
end
endaudit = AuditCallbacks.new
after_destroy audit
after_save auditclass AuditObserver < ActiveRecord::Observer
observe :snippet, :user
end
def before_save(record)
# log record.changes
end
end