Skip to content

Instantly share code, notes, and snippets.

@lucasmedeirosleite
Created October 30, 2018 15:08
Show Gist options
  • Save lucasmedeirosleite/818f96f915dedc1130e236f9feb33187 to your computer and use it in GitHub Desktop.
Save lucasmedeirosleite/818f96f915dedc1130e236f9feb33187 to your computer and use it in GitHub Desktop.
Fat model
class Product < ActiveRecord::Base
has_many :orders
validates :name, presence: true
validates :stock_level, presence: true
validates :min_stock_level, presence: true
before_validation :strip_name
before_save :notify_if_low_on_stock
after_save :notify_product_created
def low_stock?
stock_level <= min_stock_level
end
private
def strip_name
@name.strip! if @name.present?
end
def notify_if_low_on_stock
if old_stock_level >= min_stock_level && new_stock_level < min_stock_level
Notification.create message: "Buy more #{name}"
end
end
def old_stock_level
(stock_level_change.first || 0)
end
def new_stock_level
stock_level_change.last
end
def notify_product_created
Notification.create message: "Product #{name} created"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment