Skip to content

Instantly share code, notes, and snippets.

@randsina
Created August 10, 2016 14:42
Show Gist options
  • Save randsina/4c3e6496f29b4402a677a4b485344f58 to your computer and use it in GitHub Desktop.
Save randsina/4c3e6496f29b4402a677a4b485344f58 to your computer and use it in GitHub Desktop.
# == Schema Information
#
# Table name: exchanges
#
# id :integer not null, primary key
# user_id :integer
# extra_payment_to_give :decimal(10, 2)
# extra_payment_to_receive :decimal(10, 2)
# is_active :boolean default(FALSE)
# ready_to_moderate :boolean default(FALSE)
# closed_at :datetime
# published_at :datetime
# created_at :datetime not null
# updated_at :datetime not null
# adverts_count :integer
# search_requests_count :integer
# block_by_admin :boolean
# reason_of_failure :string
#
class Exchange < ActiveRecord::Base
belongs_to :user
has_many :adverts, -> { exchange_items }
has_many :search_requests, -> { exchange_items }
validates :adverts, presence: true
validates :search_requests, presence: true
scope :opened, -> { where(closed_at: nil) }
scope :ready_to_moderation, -> { where(ready_to_moderate: true) }
scope :active, -> { where(is_active: true) }
def activate!
update_attributes(is_active: true, published_at: Time.zone.now, reason_of_failure: nil)
adverts.each(&:activate!)
end
def deactivate!
update_attributes(is_active: false)
adverts.each(&:deactivate!)
end
def block
update_attributes(is_active: false, block_by_admin: true)
adverts.each(&:block)
end
def unlock
update_attributes(is_active: true, block_by_admin: false)
adverts.each(&:unlock)
end
def published?
published_at.present?
end
def opened?
closed_at.blank?
end
def inactive?
opened? && !is_active?
end
def draft?
!published? && !ready_to_moderate? && inactive?
end
def on_moderation?
ready_to_moderate? && inactive?
end
def extra_payment_to_give= val
super normalize_price(val)
end
def extra_payment_to_receive= val
super normalize_price(val)
end
def normalize_price(val)
return unless val.is_a?(String) && val.present?
val.delete(' ').to_f
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment