Skip to content

Commit

Permalink
use rails 3 idioms
Browse files Browse the repository at this point in the history
  • Loading branch information
Doug Youch committed Mar 18, 2011
1 parent b0615ab commit 7a2c297
Show file tree
Hide file tree
Showing 9 changed files with 91 additions and 77 deletions.
18 changes: 10 additions & 8 deletions app/models/domain.rb
Expand Up @@ -39,6 +39,11 @@ class Domain < SystemModel
before_create :set_inactive_message
after_save :save_database

def self.by_database(db); self.where(:database => db); end
scope :initialized, where(:status => 'initialized')
scope :type_domain, where(:domain_type => 'domain')
scope :with_database, where('`database` != "" AND `database` IS NOT NULL')

def set_inactive_message #:nodoc:
self.inactive_message = 'Site Currently Down for Maintenance' if self.inactive_message.blank?
end
Expand Down Expand Up @@ -92,7 +97,7 @@ def self.get_client_domains(client_id,*args)

# Returns a list of active modules
def get_active_modules
self.domain_modules.find(:all, :conditions => 'status = "active"', :order => 'name')
self.domain_modules.active.order('name').all
end


Expand All @@ -118,12 +123,12 @@ def self.current_site_domains

# Return a list of all domains on a given database
def self.find_site_domains(database_name)
self.find(:all,:conditions => { :database => database_name }, :order => 'name')
self.by_database(database_name).order('name').all
end

# Return a single domain on a given database
def self.find_site_domain(domain_id,database_name)
self.find(domain_id,:conditions => { :database => database_name })
self.by_database(database_name).find domain_id
end

# Return the name of the version active on this domain
Expand All @@ -141,10 +146,7 @@ def version
end

def destroy_domain #:nodoc:
dmns = Domain.find(:all,:conditions => { :database => self.database })
if dmns.length > 1
self.destroy
end
self.destroy if Domain.by_database(self.database).count > 1
end

# Make this the primary domain
Expand Down Expand Up @@ -197,7 +199,7 @@ def save_database_file
end

def self.each(env='production', ids=nil)
domains = Domain.find(:all, :conditions => 'domain_type = "domain" AND `database` != "" AND `status`="initialized"').collect { |dmn| dmn.get_info }.uniq
domains = Domain.type_domain.with_database.initialized.all.collect { |dmn| dmn.get_info }.uniq
domains.each do |dmn|
ActiveRecord::Base.establish_connection(dmn[:domain_database][:options][env])
DomainModel.activate_domain(dmn, env)
Expand Down
2 changes: 1 addition & 1 deletion app/models/domain_model.rb
Expand Up @@ -698,7 +698,7 @@ def generate_url(field,value)
permalink_try = permalink_try_partial[0..60]

if !field.blank?
while(self.class.send("find_by_#{field}",permalink_try,:conditions => ['id != ?',self.id || 0] ))
while(self.class.where('id != ?',self.id || 0).where(field => permalink_try).first)
permalink_try = permalink_try_partial + '-' + idx.to_s
idx += 1
end
Expand Down
66 changes: 33 additions & 33 deletions app/models/domain_module.rb
Expand Up @@ -7,40 +7,42 @@ class DomainModule < SystemModel

belongs_to :domain

scope :active, where(:status => 'active')

# Return information about module availability on a single Domain object
def self.module_info(domain,module_name)
# Get the class constant
module_class = "#{module_name.camelcase}::AdminController".constantize
# Get the DomainModule entry
module_entry = domain.domain_modules.find_by_name(module_name)
module_entry||= DomainModule.new( :name => module_name, :access => 'none' )
# Get the info about the whole
component_info = module_class.get_component_info
module_status= :unavailable
case module_entry.access
when 'none':
if component_info[1][:access].to_sym == 'hidden'
module_status='hidden'
else
module_status = component_info[1][:access].to_sym == :private ? 'unavailable' : 'available'
end
when 'available':
module_status = 'available'
when 'unavailable':
module_status = 'unavailable'
end

{ :module => module_name,
:name => component_info[0],
:description => component_info[1][:description],
:dependencies => component_info[1][:dependencies] || [],
:status => module_status
}
# Get the class constant
module_class = "#{module_name.camelcase}::AdminController".constantize

# Get the DomainModule entry
module_entry = domain.domain_modules.find_by_name(module_name)
module_entry||= DomainModule.new( :name => module_name, :access => 'none' )

# Get the info about the whole
component_info = module_class.get_component_info

module_status = 'unavailable'
case module_entry.access
when 'none'
if component_info[1][:access].to_sym == 'hidden'
module_status = 'hidden'
else
module_status = component_info[1][:access].to_sym == :private ? 'unavailable' : 'available'
end
when 'available'
module_status = 'available'
when 'unavailable'
module_status = 'unavailable'
end
{ :module => module_name,
:name => component_info[0],
:description => component_info[1][:description],
:dependencies => component_info[1][:dependencies] || [],
:status => module_status
}
end

# Return a list of a modules on a Domain object that
# aren't hidden
def self.all_modules(domain)
Expand All @@ -53,6 +55,4 @@ def self.all_modules(domain)
end
modules
end


end
22 changes: 15 additions & 7 deletions app/models/editor_widget.rb
Expand Up @@ -18,7 +18,16 @@ class EditorWidget < DomainModel

before_validation(:on => :create) { self.module, self.widget = self.widget_identifier.split(":") unless self.widget_identifier.blank? }

def after_create
after_create :update_editor_widget_positions

scope :with_widget, where('site_widget_id IS NOT NULL')
def self.for_column(column); self.where(:column => column); end
def self.for_user(user)
user = user.id if user.is_a?(EndUser)
self.where(:end_user_id => user)
end

def update_editor_widget_positions
EditorWidget.update_all('`position`=`position`+1',['`column`=? AND `end_user_id`=? AND `position` >= ?',self.column,self.end_user_id,self.position])
end

Expand Down Expand Up @@ -89,15 +98,15 @@ def title_link
end

def self.next_widget_position(user,column) #:nodoc:
(EditorWidget.maximum(:position,:conditions => { :end_user_id => user, :column => column } ) || -1) + 1
(EditorWidget.for_user(user).for_column(column).maximum(:position) || -1) + 1
end

def self.site_widgets(user) #:nodoc:
EditorWidget.find(:all,:conditions =>[ 'end_user_id = ? AND site_widget_id IS NOT NULL',user.id ])
EditorWidget.for_user(user).with_widget.all
end

def self.user_widgets(user) #:nodoc:
EditorWidget.find(:all,:conditions =>[ 'end_user_id = ? ',user.id ])
EditorWidget.for_user(user).all
end


Expand All @@ -116,7 +125,7 @@ def self.assemble_widgets(user) #:nodoc:
end
end
existing_widgets = editor_widgets.index_by(&:site_widget_id)
SiteWidget.find(:all,:order => :weight).each do |widget|
SiteWidget.order('weight').all.each do |widget|
if widget.view_permission_granted?(user)
if(!existing_widgets[widget.id])
widget.create_user_widget(user)
Expand All @@ -126,8 +135,7 @@ def self.assemble_widgets(user) #:nodoc:
cache_put_list("UserWidgets:#{user.id}",Time.now)
end

all_widgets = EditorWidget.find(:all,:conditions => { :end_user_id => user.id },
:order => :position,:include => :site_widget)
all_widgets = EditorWidget.for_user(user).order('position').includes(:site_widget).all
columns = [[],[],[] ]
all_widgets.each do |widget|
if widget.permission?(user)
Expand Down
24 changes: 13 additions & 11 deletions app/models/end_user.rb
Expand Up @@ -146,6 +146,11 @@ module UserLevel

after_save :update_cache

scope :activated, where(:activated => true)
scope :registered, where(:registered => true)
def self.with_login(fld, val); self.where("#{fld} != \"\" AND fld = ?", val); end
def self.by_verification_string(str); self.where(:verification_string => str); end

def update_cache #:nodoc:
self.end_user_cache = EndUserCache.find_by_end_user_id(self.id) unless self.end_user_cache
self.end_user_cache ? self.end_user_cache.save : EndUserCache.create(:end_user_id => self.id)
Expand Down Expand Up @@ -245,8 +250,7 @@ def add_token!(tkn,options = { })

# Return a list of select options of all users
def self.select_options(editor=false)
self.find(:all, :order => 'last_name, first_name',:include => :user_class,
:conditions => [ 'user_classes.editor = ?',editor ] ).collect { |usr| [ "#{usr.last_name}, #{usr.first_name} (##{usr.id})", usr.id ] }
self.includes(:user_class).where('user_classes.editor = ?',editor).order('last_name, first_name').collect { |usr| [ "#{usr.last_name}, #{usr.first_name} (##{usr.id})", usr.id ] }
end

# Return the image associated with this user or return the missing_image configured
Expand Down Expand Up @@ -299,7 +303,7 @@ def custom_action(action_name,description, opts = {})
# Given a email and a password, return a registered and active EndUser
# that matches those account details
def self.login_by_email(email,password)
usr = find(:first,:conditions => ["email != '' AND email = ? AND activated = 1 AND registered = 1",email.to_s.downcase] )
usr = self.activated.registered.with_login('email', email).first

hashed_password = EndUser.hash_password(password || "",usr.salt) if usr
if usr && usr.hashed_password == hashed_password
Expand All @@ -312,8 +316,8 @@ def self.login_by_email(email,password)
# Given a username and a password, return a registered and active EndUser
# that matches those account details
def self.login_by_username(username,password)
usr = find(:first,
:conditions => ["username != '' AND username = ? and activated = 1 AND registered = 1", username])
usr = self.activated.registered.with_login('username', username).first

hashed_password = EndUser.hash_password(password || "",usr.salt) if usr
if usr && usr.hashed_password == hashed_password
usr
Expand All @@ -325,12 +329,10 @@ def self.login_by_username(username,password)
# Login via a one-time verification string - used to reset a users password via an email ink
def self.login_by_verification(verification)
return nil if verification.blank?
usr=nil
usr = nil
EndUser.transaction do
usr = EndUser.find_by_verification_string(verification,:conditions => { :activated => 1, :registered => 1 })
if usr
usr.update_attribute(:verification_string,nil)
end
usr = EndUser.activated.registered.by_verification_string(verification).first
usr.update_attribute(:verification_string, nil) if usr
end
usr
end
Expand Down Expand Up @@ -900,7 +902,7 @@ def run_update_profile_photo(args)
end

def last_log_entry
@last_log_entry ||= (DomainLogEntry.find(:first, :conditions => {:user_id => self.id}, :order => 'occurred_at DESC') || DomainLogEntry.new)
@last_log_entry ||= (DomainLogEntry.where(:user_id => self.id).order('occurred_at DESC').first || DomainLogEntry.new)
end

def last_session
Expand Down
8 changes: 4 additions & 4 deletions app/models/end_user_action_segment_field.rb
Expand Up @@ -19,14 +19,14 @@ def self.sort_scope(order_by, direction)
info = UserSegment::FieldHandler.sortable_fields[order_by.to_sym]

if order_by.to_sym == :user_action
EndUserAction.scoped :order => "renderer #{direction}, action #{direction}"
EndUserAction.order("renderer #{direction}, action #{direction}")
elsif order_by.to_sym == :num_actions
sort_method = info[:sort_method]
field = info[:field]
EndUserAction.scoped(:select => "end_user_id, #{sort_method}(#{field}) as #{field}_#{sort_method}", :group => :end_user_id, :order => "#{field}_#{sort_method} #{direction}")
EndUserAction.select("end_user_id, #{sort_method}(#{field}) as #{field}_#{sort_method}").group('end_user_id').order("#{field}_#{sort_method} #{direction}")
else
field = self.user_segment_fields[order_by.to_sym][:field]
EndUserAction.scoped :order => "#{field} #{direction}"
EndUserAction.order("#{field} #{direction}")
end
end

Expand All @@ -35,7 +35,7 @@ def self.field_heading(field)
end

def self.get_handler_data(ids, fields)
EndUserAction.find(:all, :conditions => {:end_user_id => ids}).group_by(&:end_user_id)
EndUserAction.where(:end_user_id => ids).all.group_by(&:end_user_id)
end

def self.field_output(user, handler_data, field)
Expand Down
10 changes: 5 additions & 5 deletions app/models/end_user_action_segment_type.rb
Expand Up @@ -12,33 +12,33 @@ def self.select_options

def self.is(cls, group_field, field, path)
path = path.split('/')
cls.scoped(:conditions => ["#{field[0]} = ? and #{field[1]} = ?", path[0..-2].join('/').sub(/^\//, ''), path[-1]])
cls.where(field[0] => path[0..-2].join('/').sub(/^\//, ''), field[1] => path[-1])
end
end

class ActionType < UserSegment::FieldType

def self.select_options
EndUserAction.find(:all, :select => 'DISTINCT action').collect(&:action).sort
EndUserAction.select('DISTINCT action').all.collect(&:action).sort
end

register_operation :is, [['Action', :model, {:class => EndUserActionSegmentType::ActionType}]]

def self.is(cls, group_field, field, action)
cls.scoped(:conditions => ["#{field} = ?", action])
cls.where(field => action)
end
end

class RendererType < UserSegment::FieldType

def self.select_options
EndUserAction.find(:all, :select => 'DISTINCT renderer').collect(&:renderer).sort
EndUserAction.select('DISTINCT renderer').all.collect(&:renderer).sort
end

register_operation :is, [['Renderer', :model, {:class => EndUserActionSegmentType::RendererType}]]

def self.is(cls, group_field, field, renderer)
cls.scoped(:conditions => ["#{field} = ?", renderer])
cls.where(field => renderer)
end
end
end
6 changes: 4 additions & 2 deletions app/models/end_user_cache.rb
Expand Up @@ -3,9 +3,11 @@ class EndUserCache < DomainModel
belongs_to :end_user
validates_presence_of :end_user_id

scope :search, lambda { |query| {:conditions => ['MATCH (data) AGAINST (?)', query], :order => "MATCH (data) AGAINST (#{self.quote_value(query)}) DESC"} }
def self.search(query); self.where('MATCH (data) AGAINST (?)', query).order("MATCH (data) AGAINST (#{self.quote_value(query)}) DESC"); end

def before_save
before_save :update_data

def update_data
self.data = self.get_end_user_data.delete_if { |v| v.blank? }.join(' ')
end

Expand Down
12 changes: 6 additions & 6 deletions app/models/end_user_segment_type.rb
Expand Up @@ -9,7 +9,7 @@ def self.gender_options
register_operation :is, [['Gender', :option, {:options => EndUserSegmentType::GenderType.gender_options, :form_field => 'radio_buttons'}]]

def self.is(cls, group_field, field, gender)
cls.scoped(:conditions => ["#{field} = ?", gender])
cls.where(field => gender)
end
end

Expand All @@ -21,7 +21,7 @@ def self.select_options
register_operation :is, [['User Profile', :model, {:class => EndUserSegmentType::UserClassType}]]

def self.is(cls, group_field, field, user_class_id)
cls.scoped(:conditions => ["#{field} = ?", user_class_id])
cls.where(field => user_class_id)
end
end

Expand All @@ -34,19 +34,19 @@ def self.select_options
register_operation :is, [['Origin', :model, {:class => EndUserSegmentType::SourceType}]]

def self.is(cls, group_field, field, source)
cls.scoped(:conditions => ["#{field} = ?", source])
cls.where(field => source)
end
end

class LeadSourceType < UserSegment::FieldType
def self.select_options
EndUser.find(:all, :select => 'DISTINCT lead_source').collect(&:lead_source).reject { |lead_source| lead_source.blank? }.sort.collect { |source| [source, source] }
EndUser.select('DISTINCT lead_source').all.collect(&:lead_source).reject { |lead_source| lead_source.blank? }.sort.collect { |source| [source, source] }
end

register_operation :is, [['Lead Source', :model, {:class => EndUserSegmentType::LeadSourceType}]]

def self.is(cls, group_field, field, source)
cls.scoped(:conditions => ["#{field} = ?", source])
cls.where(field => source)
end
end

Expand All @@ -58,7 +58,7 @@ def self.select_options
register_operation :is, [['User Level', :array, {:class => UserLevelType}]]

def self.is(cls, group_field, field, user_level)
cls.scoped(:conditions => ["#{field} in(?)", user_level])
cls.where(field => user_level)
end
end
end

0 comments on commit 7a2c297

Please sign in to comment.