Files
mozo-backend/app/models/employee.rb
T

100 lines
2.6 KiB
Ruby

class Employee
include SimplyStored::Couch
include ActiveModel::SerializerSupport
attr_reader :settings
DEFAULT_SETTINGS = {
'manager' => false,
'active' => true,
'color' => '#3a87ad'
}
DEFAULT_SETTINGS.each do |attribute, default_value|
define_method(attribute) { settings.public_send attribute }
define_method("#{attribute}=") do |value|
#is_dirty
settings.set attribute, value
end
if default_value == true or default_value == false # boolean
define_method(:"#{attribute}?"){ public_send attribute }
end
end
#view :by_confirmation_token, key: :confirmation_token # devise confirmable
devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable #, :registerable #, :confirmable
property :unconfirmed_email
property :name
property :authentication_token
#property :email
has_many :employee_shifts, dependent: :destroy
view :by_authentication_token, key: :authentication_token
view :by_email, key: :email
class << self
def count_by_email(email)
database.view by_email(key: email, reduce: true)
end
def default_settings
DEFAULT_SETTINGS
end
end
def object_attributes
attributes.merge(settings.as_json).merge("id" => id)
end
#validates :email, email: true
has_and_belongs_to_many :suppliers, storing_keys: false
has_many :orders
has_and_belongs_to_many :lists, storing_keys: false
def enrich_with_settings(settings)
@settings = settings
self
end
alias_method :settings=, :enrich_with_settings
#alias_method :orig_save, :save
#def save(*args)
#settings.persist!
#orig_save(*args)
#end
before_save do
ensure_authentication_token
settings.persist!
end
def settings
@settings || SupplierEmployeesSettings.new(Supplier.new).for_employee(self)
end
#####################################
# Taken from devise 2.2
#####################################
# Generate new authentication token (a.k.a. "single access token").
def reset_authentication_token
self.authentication_token = self.class.authentication_token
end
# Generate new authentication token and save the record.
def reset_authentication_token!
reset_authentication_token
save(:validate => false)
end
# Generate authentication token unless already exists.
def ensure_authentication_token
reset_authentication_token if authentication_token.blank?
end
# Generate authentication token unless already exists and save the record.
def ensure_authentication_token!
reset_authentication_token! if authentication_token.blank?
end
def self.authentication_token
SecureRandom.hex(24)
end
end