Skip to content

Instantly share code, notes, and snippets.

@rebelweb
Last active May 1, 2018 18:20
Show Gist options
  • Save rebelweb/961ceedde8a452bb7d33496af73c175b to your computer and use it in GitHub Desktop.
Save rebelweb/961ceedde8a452bb7d33496af73c175b to your computer and use it in GitHub Desktop.
raisl callback example
# frozen_String_literal: true
class Thing < ApplicationRecord
validates :name, presence: true
# can use before_create, before_save, before_update, after_save, after_create,
# after_update, before_validation, after_validation
# also accepts if/unless
before_save :set_bool #, if: proc { |thing| thing.name == 'TEST' }
private
def set_bool
name == 'TEST' ? this.bool = true : this.bool = false
end
end
# frozen_string_literal: true
require 'test_helper'
class ThingTest < ActiveSupport::TestCase
test 'sets bool false' do
thing = Thing.new(name: 'Test')
thing.run_callbacks(:save)
refute thing.bool
end
test 'sets bool true' do
thing = Thing.new(name: 'TEST')
thing.run_callbacks(:save)
assert thing.bool
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment