2010-04-09 09:23:41 +00:00
|
|
|
class Site
|
|
|
|
include Mongoid::Document
|
|
|
|
include Mongoid::Timestamps
|
|
|
|
|
|
|
|
## fields ##
|
|
|
|
field :name
|
2010-04-10 15:25:07 +00:00
|
|
|
field :subdomain, :type => String
|
2010-04-09 09:23:41 +00:00
|
|
|
field :domains, :type => Array, :default => []
|
2010-04-13 13:24:12 +00:00
|
|
|
field :account_ids, :type => Array, :default => []
|
2010-04-09 09:23:41 +00:00
|
|
|
|
|
|
|
## validations ##
|
2010-04-10 15:25:07 +00:00
|
|
|
validates_presence_of :name, :subdomain
|
|
|
|
validates_uniqueness_of :subdomain
|
2010-04-11 23:59:18 +00:00
|
|
|
validates_exclusion_of :subdomain, :in => Locomotive.config.reserved_subdomains
|
2010-04-10 15:25:07 +00:00
|
|
|
validates_format_of :subdomain, :with => Locomotive::Regexps::SUBDOMAIN, :allow_blank => true
|
|
|
|
validate :domains_must_be_valid_and_unique
|
|
|
|
|
|
|
|
## callbacks ##
|
|
|
|
before_save :add_subdomain_to_domains
|
|
|
|
|
|
|
|
## named scopes ##
|
|
|
|
named_scope :match_domain, lambda { |domain| { :where => { :domains => domain } } }
|
|
|
|
named_scope :match_domain_with_exclusion_of, lambda { |domain, site| { :where => { :domains => domain, :id.ne => site.id } } }
|
2010-04-09 09:23:41 +00:00
|
|
|
|
|
|
|
## behaviours ##
|
2010-04-10 15:25:07 +00:00
|
|
|
add_dirty_methods :domains
|
2010-04-09 09:23:41 +00:00
|
|
|
|
|
|
|
## methods ##
|
2010-04-13 13:24:12 +00:00
|
|
|
|
|
|
|
def accounts
|
|
|
|
Account.criteria.in(:_id => self.account_ids)
|
|
|
|
end
|
|
|
|
|
|
|
|
def accounts=(models_or_ids)
|
|
|
|
self.account_ids = [*models_or_ids].collect { |object| object.respond_to?(:to_i) ? object : object.id }.uniq
|
|
|
|
end
|
2010-04-09 09:23:41 +00:00
|
|
|
|
2010-04-10 15:25:07 +00:00
|
|
|
def add_subdomain_to_domains
|
|
|
|
self.domains ||= []
|
2010-04-11 23:59:18 +00:00
|
|
|
(self.domains << "#{self.subdomain}.#{Locomotive.config.default_domain}").uniq!
|
2010-04-10 15:25:07 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def domains_without_subdomain
|
2010-04-11 23:59:18 +00:00
|
|
|
(self.domains || []) - ["#{self.subdomain}.#{Locomotive.config.default_domain}"]
|
2010-04-09 09:23:41 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
protected
|
|
|
|
|
2010-04-10 15:25:07 +00:00
|
|
|
def domains_must_be_valid_and_unique
|
|
|
|
return if self.domains.empty? || (!self.new_record? && !self.domains_changed?)
|
|
|
|
|
|
|
|
(self.domains_without_subdomain - (self.domains_was || [])) .each do |domain|
|
|
|
|
if not self.class.match_domain_with_exclusion_of(domain, self).first.nil?
|
|
|
|
self.errors.add(:domains, :domain_taken, :value => domain)
|
|
|
|
end
|
|
|
|
|
|
|
|
if not domain =~ Locomotive::Regexps::DOMAIN
|
|
|
|
self.errors.add(:domains, :invalid_domain, :value => domain)
|
|
|
|
end
|
|
|
|
end
|
2010-04-09 09:23:41 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
end
|