diff --git a/Gemfile b/Gemfile index 9a04094..9b9c2f5 100644 --- a/Gemfile +++ b/Gemfile @@ -52,7 +52,6 @@ gem 'protected_attributes' gem 'rails-observers' gem 'actionpack-page_caching' gem 'actionpack-action_caching' -gem 'activerecord-deprecated_finders', require: 'active_record/deprecated_finders' group :production do gem 'dalli', '~> 2.7.0' diff --git a/app/controllers/admin/admin_panel_controller.rb b/app/controllers/admin/admin_panel_controller.rb index 32f67ac..417351f 100644 --- a/app/controllers/admin/admin_panel_controller.rb +++ b/app/controllers/admin/admin_panel_controller.rb @@ -34,7 +34,7 @@ class AdminPanelController < AdminController env = environment @portal_community = env.portal_community || Community.new if request.post? - portal_community = env.communities.find_by_identifier(params[:portal_community_identifier]) + portal_community = env.communities.where(identifier: params[:portal_community_identifier]).first if portal_community if (env.portal_community != portal_community) env.portal_community = portal_community diff --git a/app/controllers/admin/environment_role_manager_controller.rb b/app/controllers/admin/environment_role_manager_controller.rb index 67822e5..68dcbf0 100644 --- a/app/controllers/admin/environment_role_manager_controller.rb +++ b/app/controllers/admin/environment_role_manager_controller.rb @@ -7,7 +7,7 @@ class EnvironmentRoleManagerController < AdminController def change_roles @admin = Person.find(params[:id]) - @roles = Role.find(:all).select{ |r| r.has_kind?(:environment) } + @roles = Role.all.select{ |r| r.has_kind?(:environment) } end def update_roles @@ -22,7 +22,7 @@ class EnvironmentRoleManagerController < AdminController end def change_role - @roles = Role.find(:all).select{ |r| r.has_kind?(:environment) } + @roles = Role.all.select{ |r| r.has_kind?(:environment) } @admin = Person.find(params[:id]) @associations = @admin.find_roles(environment) end @@ -34,7 +34,7 @@ class EnvironmentRoleManagerController < AdminController redirect_to :action => 'index' else @admin = Person.find(params[:person]) - @roles = Role.find(:all).select{ |r| r.has_kind?(:environment) } + @roles = Role.all.select{ |r| r.has_kind?(:environment) } render :action => 'affiliate' end end @@ -60,7 +60,7 @@ class EnvironmentRoleManagerController < AdminController end def make_admin - @people = Person.find(:all) - @roles = Role.find(:all).select{|r|r.has_kind?(:environment)} + @people = Person.all + @roles = Role.all.select{|r|r.has_kind?(:environment)} end end diff --git a/app/controllers/admin/features_controller.rb b/app/controllers/admin/features_controller.rb index 22566e3..f51de3a 100644 --- a/app/controllers/admin/features_controller.rb +++ b/app/controllers/admin/features_controller.rb @@ -60,7 +60,7 @@ class FeaturesController < AdminController CustomField.destroy(custom_fields_to_destroy) custom_field_list.each_pair do |id, custom_field| - field = CustomField.find_by_id(id) + field = CustomField.find_by(id: id) if not field.blank? params_to_update = custom_field.except(:format, :extras, :customized_type,:environment) field.update_attributes(params_to_update) diff --git a/app/controllers/admin/role_controller.rb b/app/controllers/admin/role_controller.rb index fd3b1d9..73d840e 100644 --- a/app/controllers/admin/role_controller.rb +++ b/app/controllers/admin/role_controller.rb @@ -2,7 +2,7 @@ class RoleController < AdminController protect 'manage_environment_roles', :environment def index - @roles = environment.roles.find(:all, :conditions => {:profile_id => nil}) + @roles = environment.roles.where profile_id: nil end def new diff --git a/app/controllers/admin/users_controller.rb b/app/controllers/admin/users_controller.rb index 8e1e47c..111f4de 100644 --- a/app/controllers/admin/users_controller.rb +++ b/app/controllers/admin/users_controller.rb @@ -48,7 +48,7 @@ class UsersController < AdminController def destroy_user if request.post? - person = environment.people.find_by_id(params[:id]) + person = environment.people.find_by id: params[:id] if person && person.destroy session[:notice] = _('The profile was deleted.') else diff --git a/app/controllers/application_controller.rb b/app/controllers/application_controller.rb index b226fae..27c8132 100644 --- a/app/controllers/application_controller.rb +++ b/app/controllers/application_controller.rb @@ -123,7 +123,7 @@ class ApplicationController < ActionController::Base # Sets text domain based on request host for custom internationalization FastGettext.text_domain = Domain.custom_locale(request.host) - @domain = Domain.find_by_name(request.host) + @domain = Domain.by_name(request.host) if @domain.nil? @environment = Environment.default # Avoid crashes on test and development setups @@ -138,7 +138,7 @@ class ApplicationController < ActionController::Base # Check if the requested profile belongs to another domain if @profile && !params[:profile].blank? && params[:profile] != @profile.identifier - @profile = @environment.profiles.find_by_identifier params[:profile] + @profile = @environment.profiles.find_by(identifier: params[:profile]) redirect_to url_for(params.merge host: @profile.default_hostname) end end @@ -170,7 +170,7 @@ class ApplicationController < ActionController::Base def load_category unless params[:category_path].blank? path = params[:category_path] - @category = environment.categories.find_by_path(path) + @category = environment.categories.find_by(path: path) if @category.nil? render_not_found(path) end diff --git a/app/controllers/box_organizer_controller.rb b/app/controllers/box_organizer_controller.rb index c76cbcc..557c6ed 100644 --- a/app/controllers/box_organizer_controller.rb +++ b/app/controllers/box_organizer_controller.rb @@ -16,10 +16,9 @@ class BoxOrganizerController < ApplicationController target_position = block_before.position @target_box = block_before.box - else - (params[:target] =~ /end-of-box-([0-9]+)/) + elsif params[:target] =~ /end-of-box-([0-9]+)/ - @target_box = boxes_holder.boxes.find_by_id($1) + @target_box = boxes_holder.boxes.find_by id: $1 end @block = new_block(params[:type], @target_box) if @block.nil? @@ -35,8 +34,8 @@ class BoxOrganizerController < ApplicationController @block.insert_at(@target_box.blocks.size + 1) @block.move_to_bottom else - # insert the block in the given position - @block.insert_at(@block.position && @block.position < target_position ? target_position - 1 : target_position) + new_position = if @block.position and @block.position < target_position then target_position - 1 else target_position end + @block.insert_at new_position end @block.save! diff --git a/app/controllers/my_profile/cms_controller.rb b/app/controllers/my_profile/cms_controller.rb index 4d55fed..b218b11 100644 --- a/app/controllers/my_profile/cms_controller.rb +++ b/app/controllers/my_profile/cms_controller.rb @@ -34,7 +34,7 @@ class CmsController < MyProfileController protect_if :only => [:new, :upload_files] do |c, user, profile| parent_id = c.params[:article].present? ? c.params[:article][:parent_id] : c.params[:parent_id] - parent = profile.articles.find_by_id(parent_id) + parent = profile.articles.find_by(id: parent_id) user && user.can_post_content?(profile, parent) end @@ -59,11 +59,10 @@ class CmsController < MyProfileController def index @article = nil - @articles = profile.top_level_articles.paginate( - :order => "case when type = 'Folder' then 0 when type ='Blog' then 1 else 2 end, updated_at DESC", - :per_page => per_page, - :page => params[:npage] - ) + @articles = profile.top_level_articles + .order("case when type = 'Folder' then 0 when type ='Blog' then 1 else 2 end, updated_at DESC") + .paginate(per_page: per_page, page: params[:npage]) + render :action => 'view' end diff --git a/app/controllers/my_profile/friends_controller.rb b/app/controllers/my_profile/friends_controller.rb index 3b44de1..6a5f6d5 100755 --- a/app/controllers/my_profile/friends_controller.rb +++ b/app/controllers/my_profile/friends_controller.rb @@ -22,7 +22,7 @@ class FriendsController < MyProfileController end def remove_suggestion - @person = profile.suggested_people.find_by_identifier(params[:id]) + @person = profile.suggested_people.find_by(identifier: params[:id]) redirect_to :action => 'suggest' unless @person if @person && request.post? profile.remove_suggestion(@person) @@ -32,7 +32,7 @@ class FriendsController < MyProfileController end def connections - @suggestion = profile.suggested_profiles.of_person.enabled.find_by_suggestion_id(params[:id]) + @suggestion = profile.suggested_profiles.of_person.enabled.find_by(suggestion_id: params[:id]) if @suggestion @tags = @suggestion.tag_connections @profiles = @suggestion.profile_connections diff --git a/app/controllers/my_profile/manage_products_controller.rb b/app/controllers/my_profile/manage_products_controller.rb index 2f28c8f..6e06d0a 100644 --- a/app/controllers/my_profile/manage_products_controller.rb +++ b/app/controllers/my_profile/manage_products_controller.rb @@ -35,7 +35,7 @@ class ManageProductsController < ApplicationController end def categories_for_selection - @category = environment.categories.find_by_id params[:category_id] + @category = environment.categories.find_by id: params[:category_id] @object_name = params[:object_name] if @category @categories = @category.children @@ -103,7 +103,7 @@ class ManageProductsController < ApplicationController def search_categories @term = params[:term].downcase conditions = ['LOWER(name) LIKE ? OR LOWER(name) LIKE ?', "#{@term}%", "% #{@term}%"] - @categories = ProductCategory.all :conditions => conditions, :limit => 10 + @categories = ProductCategory.where(conditions).limit(10) render :json => (@categories.map do |category| {:label => category.name, :value => category.id} end) @@ -169,7 +169,7 @@ class ManageProductsController < ApplicationController def edit_input if request.xhr? - @input = @profile.inputs.find_by_id(params[:id]) + @input = @profile.inputs.find_by id: params[:id] if @input if request.post? if @input.update(params[:input]) diff --git a/app/controllers/my_profile/memberships_controller.rb b/app/controllers/my_profile/memberships_controller.rb index c4d24d4..4206620 100644 --- a/app/controllers/my_profile/memberships_controller.rb +++ b/app/controllers/my_profile/memberships_controller.rb @@ -5,7 +5,7 @@ class MembershipsController < MyProfileController def index @roles = environment.roles.select do |role| - ra = profile.role_assignments.find_by_role_id(role.id) + ra = profile.role_assignments.find_by(role_id: role.id) ra.present? && ra.resource_type == 'Profile' end @filter = params[:filter_type].to_i @@ -47,7 +47,7 @@ class MembershipsController < MyProfileController end def remove_suggestion - @community = profile.suggested_communities.find_by_identifier(params[:id]) + @community = profile.suggested_communities.find_by(identifier: params[:id]) custom_per_page = params[:per_page] || per_page redirect_to :action => 'suggest' unless @community if @community && request.post? @@ -58,7 +58,7 @@ class MembershipsController < MyProfileController end def connections - @suggestion = profile.suggested_profiles.of_community.enabled.find_by_suggestion_id(params[:id]) + @suggestion = profile.suggested_profiles.of_community.enabled.find_by(suggestion_id: params[:id]) if @suggestion @tags = @suggestion.tag_connections @profiles = @suggestion.profile_connections diff --git a/app/controllers/my_profile/profile_members_controller.rb b/app/controllers/my_profile/profile_members_controller.rb index ff84cdb..07e9559 100644 --- a/app/controllers/my_profile/profile_members_controller.rb +++ b/app/controllers/my_profile/profile_members_controller.rb @@ -60,7 +60,7 @@ class ProfileMembersController < MyProfileController redirect_to :action => 'index' else @member = Person.find(params[:person]) - @roles = environment.roles.find(:all).select{ |r| r.has_kind?('Profile') } + @roles = environment.roles.all.select{ |r| r.has_kind?('Profile') } render :action => 'affiliate' end end @@ -120,7 +120,7 @@ class ProfileMembersController < MyProfileController @collection = :profile_admins if profile.community? - member = profile.members.find_by_identifier(params[:id]) + member = profile.members.find_by(identifier: params[:id]) profile.add_admin(member) end render :layout => false @@ -131,7 +131,7 @@ class ProfileMembersController < MyProfileController @collection = :profile_admins if profile.community? - member = profile.members.find_by_identifier(params[:id]) + member = profile.members.find_by(identifier: params[:id]) profile.remove_admin(member) end render :layout => false diff --git a/app/controllers/my_profile/spam_controller.rb b/app/controllers/my_profile/spam_controller.rb index 0a8aa51..0a071c6 100644 --- a/app/controllers/my_profile/spam_controller.rb +++ b/app/controllers/my_profile/spam_controller.rb @@ -15,12 +15,12 @@ class SpamController < MyProfileController profile.comments_received.find(params[:remove_comment]).destroy end if params[:remove_task] - Task.to(profile).find_by_id(params[:remove_task]).destroy + Task.to(profile).find_by(id: params[:remove_task]).destroy end if params[:mark_comment_as_ham] profile.comments_received.find(params[:mark_comment_as_ham]).ham! end - if params[:mark_task_as_ham] && (t = Task.to(profile).find_by_id(params[:mark_task_as_ham])) + if params[:mark_task_as_ham] && (t = Task.to(profile).find_by(id: params[:mark_task_as_ham])) t.ham! end if request.xhr? diff --git a/app/controllers/my_profile/tasks_controller.rb b/app/controllers/my_profile/tasks_controller.rb index 5dfce4d..ef35414 100644 --- a/app/controllers/my_profile/tasks_controller.rb +++ b/app/controllers/my_profile/tasks_controller.rb @@ -7,8 +7,8 @@ class TasksController < MyProfileController helper CustomFieldsHelper def index - @rejection_email_templates = profile.email_templates.find_all_by_template_type(:task_rejection) - @acceptance_email_templates = profile.email_templates.find_all_by_template_type(:task_acceptance) + @rejection_email_templates = profile.email_templates.where template_type: :task_rejection + @acceptance_email_templates = profile.email_templates.where template_type: :task_acceptance @filter_type = params[:filter_type].presence @filter_text = params[:filter_text].presence @@ -88,7 +88,7 @@ class TasksController < MyProfileController end def list_requested - @tasks = Task.without_spam.find_all_by_requestor_id(profile.id) + @tasks = Task.without_spam.where requestor_id: profile.id end def ticket_details diff --git a/app/controllers/public/account_controller.rb b/app/controllers/public/account_controller.rb index 9407463..3eb6021 100644 --- a/app/controllers/public/account_controller.rb +++ b/app/controllers/public/account_controller.rb @@ -17,7 +17,7 @@ class AccountController < ApplicationController end def activate - @user = User.find_by_activation_code(params[:activation_code]) if params[:activation_code] + @user = User.find_by(activation_code: params[:activation_code]) if params[:activation_code] if @user unless @user.environment.enabled?('admin_must_approve_new_users') if @user.activate @@ -118,7 +118,7 @@ class AccountController < ApplicationController end @user.community_to_join = session[:join] @user.signup! - owner_role = Role.find_by_name('owner') + owner_role = Role.find_by(name: 'owner') @user.person.affiliate(@user.person, [owner_role]) if owner_role invitation = Task.from_code(@invitation_code).first if invitation @@ -305,7 +305,7 @@ class AccountController < ApplicationController end def check_email - if User.find_by_email_and_environment_id(params[:address], environment.id).nil? + if User.find_by(email: params[:address], environment_id: environment.id).nil? @status = _('This e-mail address is available') @status_class = 'validated' else @@ -502,7 +502,7 @@ class AccountController < ApplicationController def check_join_in_community(user) profile_to_join = session[:join] unless profile_to_join.blank? - environment.profiles.find_by_identifier(profile_to_join).add_member(user.person) + environment.profiles.find_by(identifier: profile_to_join).add_member(user.person) session.delete(:join) end end diff --git a/app/controllers/public/chat_controller.rb b/app/controllers/public/chat_controller.rb index ebe0a9b..a673b27 100644 --- a/app/controllers/public/chat_controller.rb +++ b/app/controllers/public/chat_controller.rb @@ -44,7 +44,7 @@ class ChatController < PublicController end def avatar - profile = environment.profiles.find_by_identifier(params[:id]) + profile = environment.profiles.find_by(identifier: params[:id]) filename, mimetype = profile_icon(profile, :minor, true) if filename =~ /^(https?:)?\/\// redirect_to filename @@ -87,7 +87,7 @@ class ChatController < PublicController end def recent_messages - other = environment.profiles.find_by_identifier(params[:identifier]) + other = environment.profiles.find_by(identifier: params[:identifier]) if other.kind_of?(Organization) messages = ChatMessage.where('to_id=:other', :other => other.id) else diff --git a/app/controllers/public/content_viewer_controller.rb b/app/controllers/public/content_viewer_controller.rb index c186ead..433ff14 100644 --- a/app/controllers/public/content_viewer_controller.rb +++ b/app/controllers/public/content_viewer_controller.rb @@ -18,7 +18,7 @@ class ContentViewerController < ApplicationController @page = profile.home_page return if redirected_to_profile_index else - @page = profile.articles.find_by_path(path) + @page = profile.articles.find_by path: path return if redirected_page_from_old_path(path) end @@ -76,13 +76,13 @@ class ContentViewerController < ApplicationController def versions_diff path = params[:page] - @page = profile.articles.find_by_path(path) - @v1, @v2 = @page.versions.find_by_version(params[:v1]), @page.versions.find_by_version(params[:v2]) + @page = profile.articles.find_by path: path + @v1, @v2 = @page.versions.find_by(version: params[:v1]), @page.versions.find_by(version: params[:v2]) end def article_versions path = params[:page] - @page = profile.articles.find_by_path(path) + @page = profile.articles.find_by path: path return unless allow_access_to_page(path) render_access_denied unless @page.display_versions? @@ -169,7 +169,7 @@ class ContentViewerController < ApplicationController def redirected_page_from_old_path(path) unless @page - page_from_old_path = profile.articles.find_by_old_path(path) + page_from_old_path = profile.articles.find_by_old_path path if page_from_old_path redirect_to profile.url.merge(:page => page_from_old_path.explode_path) return true @@ -190,7 +190,7 @@ class ContentViewerController < ApplicationController end def rendered_versioned_article - @versioned_article = @page.versions.find_by_version(@version) + @versioned_article = @page.versions.find_by version: @version if @versioned_article && @page.versions.latest.version != @versioned_article.version render :template => 'content_viewer/versioned_article.html.erb' return true diff --git a/app/controllers/public/enterprise_registration_controller.rb b/app/controllers/public/enterprise_registration_controller.rb index 7b58c57..4ba8421 100644 --- a/app/controllers/public/enterprise_registration_controller.rb +++ b/app/controllers/public/enterprise_registration_controller.rb @@ -68,7 +68,7 @@ class EnterpriseRegistrationController < ApplicationController # saying to the user that the enterprise was created. def creation @create_enterprise.perform - @enterprise = @create_enterprise.target.profiles.find_by_identifier(@create_enterprise.identifier) + @enterprise = @create_enterprise.target.profiles.find_by identifier: @create_enterprise.identifier end end diff --git a/app/controllers/public/profile_controller.rb b/app/controllers/public/profile_controller.rb index 0d5c99e..2c1d447 100644 --- a/app/controllers/public/profile_controller.rb +++ b/app/controllers/public/profile_controller.rb @@ -339,7 +339,7 @@ class ProfileController < PublicController user.register_report(abuse_report, profile) if !params[:content_type].blank? - abuse_report = AbuseReport.find_by_reporter_id_and_abuse_complaint_id(user.id, profile.opened_abuse_complaint.id) + abuse_report = AbuseReport.find_by(reporter_id: user.id, abuse_complaint_id: profile.opened_abuse_complaint.id) Delayed::Job.enqueue DownloadReportedImagesJob.new(abuse_report, article) end @@ -374,7 +374,7 @@ class ProfileController < PublicController def send_mail @mailing = profile.mailings.build(params[:mailing]) @mailing.data = session[:members_filtered] ? {:members_filtered => session[:members_filtered]} : {} - @email_templates = profile.email_templates.find_all_by_template_type(:organization_members) + @email_templates = profile.email_templates.where template_type: :organization_members if request.post? @mailing.locale = locale @mailing.person = user diff --git a/app/controllers/public/search_controller.rb b/app/controllers/public/search_controller.rb index f3ae44a..a9d31bd 100644 --- a/app/controllers/public/search_controller.rb +++ b/app/controllers/public/search_controller.rb @@ -167,7 +167,7 @@ class SearchController < PublicController render_not_found if params[:action] == 'category_index' else path = params[:category_path] - @category = environment.categories.find_by_path(path) + @category = environment.categories.find_by path: path if @category.nil? render_not_found(path) else @@ -177,14 +177,14 @@ class SearchController < PublicController end def available_searches - @available_searches ||= ActiveSupport::OrderedHash[ - :articles, _('Contents'), - :people, _('People'), - :communities, _('Communities'), - :enterprises, _('Enterprises'), - :products, _('Products and Services'), - :events, _('Events'), - ] + @available_searches ||= { + articles: _('Contents'), + people: _('People'), + communities: _('Communities'), + enterprises: _('Enterprises'), + products: _('Products and Services'), + events: _('Events'), + } end def load_search_assets @@ -256,13 +256,13 @@ class SearchController < PublicController end def available_assets - assets = ActiveSupport::OrderedHash[ - :articles, _('Contents'), - :enterprises, _('Enterprises'), - :people, _('People'), - :communities, _('Communities'), - :products, _('Products and Services'), - ] + assets = { + articles: _('Contents'), + enterprises: _('Enterprises'), + people: _('People'), + communities: _('Communities'), + products: _('Products and Services'), + } end end diff --git a/app/helpers/application_helper.rb b/app/helpers/application_helper.rb index f5d3e62..4a3a1c6 100644 --- a/app/helpers/application_helper.rb +++ b/app/helpers/application_helper.rb @@ -318,7 +318,7 @@ module ApplicationHelper if File.exists?(Rails.root.join('public', theme_path, 'favicon.ico')) '/designs/themes/' + profile.theme + '/favicon.ico' else - favicon = profile.articles.find_by_path('favicon.ico') + favicon = profile.articles.find_by path: 'favicon.ico' if favicon favicon.public_filename else @@ -1154,8 +1154,8 @@ module ApplicationHelper end def default_folder_for_image_upload(profile) - default_folder = profile.folders.find_by_type('Gallery') - default_folder = profile.folders.find_by_type('Folder') if default_folder.nil? + default_folder = profile.folders.find_by type: 'Gallery' + default_folder = profile.folders.find_by type: 'Folder' if default_folder.nil? default_folder end diff --git a/app/helpers/forms_helper.rb b/app/helpers/forms_helper.rb index 4ffd205..36f6885 100644 --- a/app/helpers/forms_helper.rb +++ b/app/helpers/forms_helper.rb @@ -50,15 +50,15 @@ module FormsHelper end def select_city( simple=false ) - states = State.find(:all, :order => 'name') - + states = State.order(:name).all + state_id = 'state-' + FormsHelper.next_id_number city_id = 'city-' + FormsHelper.next_id_number if states.length < 1 return end - + if simple states = [State.new(:name => _('Select the State'))] + states cities = [City.new(:name => _('Select the City'))] @@ -82,7 +82,7 @@ module FormsHelper states = [State.new(:name => '---')] + states cities = [City.new(:name => '---')] - html = + html = content_tag( 'div', labelled_select( _('State:'), 'state', :id, :name, nil, states, :id => state_id ), :class => 'select_state_for_origin' ) + @@ -90,7 +90,7 @@ module FormsHelper labelled_select( _('City:'), 'city', :id, :name, nil, cities, :id => city_id ), :class => 'select_city_for_origin' ) end - + html + observe_field( state_id, :update => city_id, :function => "new Ajax.Updater(#{city_id.inspect}, #{url_for(:controller => 'search', :action => 'cities').inspect}, {asynchronous:true, evalScripts:true, parameters:'state_id=' + value}); $(#{city_id.inspect}).innerHTML = ''", :with => 'state_id') end diff --git a/app/helpers/manage_products_helper.rb b/app/helpers/manage_products_helper.rb index 6e05369..2fe2755 100644 --- a/app/helpers/manage_products_helper.rb +++ b/app/helpers/manage_products_helper.rb @@ -222,7 +222,7 @@ module ManageProductsHelper end def select_certifiers(qualifier, product = nil) if qualifier - selected = product ? product.product_qualifiers.find_by_qualifier_id(qualifier.id).certifier_id : nil + selected = product ? product.product_qualifiers.find_by(qualifier_id: qualifier.id).certifier_id : nil select_tag("product[qualifiers_list][#{qualifier.id}]", options_for_select(certifiers_for_select(qualifier), selected)) else select_tag("product[qualifiers_list][nil]") diff --git a/app/helpers/profile_helper.rb b/app/helpers/profile_helper.rb index f9c1450..14ce947 100644 --- a/app/helpers/profile_helper.rb +++ b/app/helpers/profile_helper.rb @@ -1,11 +1,11 @@ module ProfileHelper - COMMON_CATEGORIES = ActiveSupport::OrderedHash.new + COMMON_CATEGORIES = {} COMMON_CATEGORIES[:content] = [:blogs, :image_galleries, :events, :article_tags] COMMON_CATEGORIES[:interests] = [:interests] COMMON_CATEGORIES[:general] = nil - PERSON_CATEGORIES = ActiveSupport::OrderedHash.new + PERSON_CATEGORIES = {} PERSON_CATEGORIES[:basic_information] = [:nickname, :sex, :birth_date, :location, :privacy_setting, :created_at] PERSON_CATEGORIES[:contact] = [:contact_phone, :cell_phone, :comercial_phone, :contact_information, :email, :personal_website, :jabber_id] PERSON_CATEGORIES[:location] = [:address, :address_reference, :zip_code, :city, :state, :district, :country, :nationality] @@ -14,13 +14,13 @@ module ProfileHelper PERSON_CATEGORIES[:network] = [:friends, :communities, :enterprises] PERSON_CATEGORIES.merge!(COMMON_CATEGORIES) - ORGANIZATION_CATEGORIES = ActiveSupport::OrderedHash.new + ORGANIZATION_CATEGORIES = {} ORGANIZATION_CATEGORIES[:basic_information] = [:display_name, :created_at, :foundation_year, :type, :language, :members_count, :location, :address_reference, :historic_and_current_context, :admins] ORGANIZATION_CATEGORIES[:contact] = [:contact_person, :contact_phone, :contact_email, :organization_website, :jabber_id] ORGANIZATION_CATEGORIES[:economic] = [:business_name, :acronym, :economic_activity, :legal_form, :products, :activities_short_description, :management_information] ORGANIZATION_CATEGORIES.merge!(COMMON_CATEGORIES) - CATEGORY_MAP = ActiveSupport::OrderedHash.new + CATEGORY_MAP = {} CATEGORY_MAP[:person] = PERSON_CATEGORIES CATEGORY_MAP[:organization] = ORGANIZATION_CATEGORIES diff --git a/app/models/add_friend.rb b/app/models/add_friend.rb index 930aaf7..f951204 100644 --- a/app/models/add_friend.rb +++ b/app/models/add_friend.rb @@ -57,7 +57,7 @@ class AddFriend < Task end def remove_from_suggestion_list(task) - suggestion = task.requestor.suggested_profiles.find_by_suggestion_id task.target.id + suggestion = task.requestor.suggested_profiles.find_by suggestion_id: task.target.id suggestion.disable if suggestion end end diff --git a/app/models/add_member.rb b/app/models/add_member.rb index a33072a..9e11b60 100644 --- a/app/models/add_member.rb +++ b/app/models/add_member.rb @@ -59,7 +59,7 @@ class AddMember < Task end def remove_from_suggestion_list(task) - suggestion = task.requestor.profile_suggestions.find_by_suggestion_id task.target.id + suggestion = task.requestor.profile_suggestions.find_by suggestion_id: task.target.id suggestion.disable if suggestion end diff --git a/app/models/approve_article.rb b/app/models/approve_article.rb index a5641b4..803cbe3 100644 --- a/app/models/approve_article.rb +++ b/app/models/approve_article.rb @@ -20,7 +20,7 @@ class ApproveArticle < Task end def article - Article.find_by_id data[:article_id] + Article.find_by id: data[:article_id] end def article= value @@ -39,7 +39,7 @@ class ApproveArticle < Task settings_items :create_link, :type => :boolean, :default => false def article_parent - Article.find_by_id article_parent_id.to_i + Article.find_by id: article_parent_id.to_i end def article_parent= value diff --git a/app/models/approve_comment.rb b/app/models/approve_comment.rb index cadf357..3cdab4e 100644 --- a/app/models/approve_comment.rb +++ b/app/models/approve_comment.rb @@ -18,7 +18,7 @@ class ApproveComment < Task end def article - Article.find_by_id comment.source_id unless self.comment.nil? + Article.find_by id: comment.source_id unless self.comment.nil? end def article_name diff --git a/app/models/article.rb b/app/models/article.rb index 7deae38..bcb805c 100644 --- a/app/models/article.rb +++ b/app/models/article.rb @@ -74,11 +74,11 @@ class Article < ActiveRecord::Base belongs_to :last_changed_by, :class_name => 'Person', :foreign_key => 'last_changed_by_id' belongs_to :created_by, :class_name => 'Person', :foreign_key => 'created_by_id' - has_many :comments, :class_name => 'Comment', :as => 'source', :dependent => :destroy, :order => 'created_at asc' + has_many :comments, -> { order 'created_at asc' }, class_name: 'Comment', as: 'source', dependent: :destroy has_many :article_followers, :dependent => :destroy has_many :person_followers, :class_name => 'Person', :through => :article_followers, :source => :person - has_many :person_followers_emails, :class_name => 'User', :through => :person_followers, :source => :user, :select => :email + has_many :person_followers_emails, -> { select :email }, class_name: 'User', through: :person_followers, source: :user has_many :article_categorizations, -> { where 'articles_categories.virtual = ?', false } has_many :categories, :through => :article_categorizations @@ -279,7 +279,7 @@ class Article < ActiveRecord::Base # retrives the most commented articles, sorted by the comment count (largest # first) def self.most_commented(limit) - paginate(:order => 'comments_count DESC', :page => 1, :per_page => limit) + order('comments_count DESC').paginate(page: 1, per_page: limit) end scope :more_popular, -> { order 'hits DESC' } @@ -288,7 +288,7 @@ class Article < ActiveRecord::Base } def self.recent(limit = nil, extra_conditions = {}, pagination = true) - result = scoped({:conditions => extra_conditions}). + result = where(extra_conditions). is_public. relevant_as_recent. limit(limit). @@ -470,7 +470,7 @@ class Article < ActiveRecord::Base def rotate_translations unless self.translations.empty? - rotate = self.translations.all + rotate = self.translations.to_a root = rotate.shift root.update_attribute(:translation_of_id, nil) root.translations = rotate @@ -752,7 +752,7 @@ class Article < ActiveRecord::Base def version_license(version_number = nil) return license if version_number.nil? - profile.environment.licenses.find_by_id(get_version(version_number).license_id) + profile.environment.licenses.find_by(id: get_version(version_number).license_id) end alias :active_record_cache_key :cache_key diff --git a/app/models/block.rb b/app/models/block.rb index ce4909d..d2fe631 100644 --- a/app/models/block.rb +++ b/app/models/block.rb @@ -11,7 +11,8 @@ class Block < ActiveRecord::Base delegate :environment, :to => :box, :allow_nil => true - acts_as_list :scope => :box + acts_as_list scope: -> block { where box_id: block.box_id } + belongs_to :box belongs_to :mirror_block, :class_name => "Block" has_many :observers, :class_name => "Block", :foreign_key => "mirror_block_id" diff --git a/app/models/blog.rb b/app/models/blog.rb index c94763d..cb4722e 100644 --- a/app/models/blog.rb +++ b/app/models/blog.rb @@ -98,8 +98,9 @@ class Blog < Folder when :by_year posts.published.native_translations .except(:order) - .count(:all, :group => 'EXTRACT(YEAR FROM published_at)') - .sort_by {|year, count| -year.to_i} + .group('EXTRACT(YEAR FROM published_at)') + .count + .sort_by{ |year, count| -year.to_i } when :by_month posts.published.native_translations .except(:order) diff --git a/app/models/box.rb b/app/models/box.rb index 57a6174..45dad95 100644 --- a/app/models/box.rb +++ b/app/models/box.rb @@ -1,7 +1,9 @@ class Box < ActiveRecord::Base + + acts_as_list scope: -> box { where owner_id: box.owner_id, owner_type: box.owner_type } + belongs_to :owner, :polymorphic => true - acts_as_list :scope => 'owner_id = #{owner_id} and owner_type = \'#{owner_type}\'' - has_many :blocks, :dependent => :destroy, :order => 'position' + has_many :blocks, -> { order 'position' }, dependent: :destroy attr_accessible :owner diff --git a/app/models/category.rb b/app/models/category.rb index adc91d4..07acc00 100644 --- a/app/models/category.rb +++ b/app/models/category.rb @@ -90,7 +90,7 @@ class Category < ActiveRecord::Base def children_for_menu results = [] - pending = children.where(display_in_menu: true).all + pending = children.where(display_in_menu: true).to_a while pending.present? cat = pending.shift results << cat diff --git a/app/models/comment.rb b/app/models/comment.rb index ce8eed2..961c79a 100644 --- a/app/models/comment.rb +++ b/app/models/comment.rb @@ -92,7 +92,7 @@ class Comment < ActiveRecord::Base end def self.recent(limit = nil) - self.find(:all, :order => 'created_at desc, id desc', :limit => limit) + self.order('created_at desc, id desc').limit(limit).all end def notification_emails diff --git a/app/models/community.rb b/app/models/community.rb index aa45ea7..b4fb5cf 100644 --- a/app/models/community.rb +++ b/app/models/community.rb @@ -77,7 +77,7 @@ class Community < Organization end def each_member(offset=0) - while member = self.members.first(:order => :id, :offset => offset) + while member = self.members.order(:id).offset(offset).first yield member offset = offset + 1 end diff --git a/app/models/domain.rb b/app/models/domain.rb index f368c5c..59e9d6b 100644 --- a/app/models/domain.rb +++ b/app/models/domain.rb @@ -36,8 +36,8 @@ class Domain < ActiveRecord::Base # finds a domain by its name. The argument name can start with # "www.", but it will be removed before searching. So searching for # 'www.example.net' is exactly the same as searching for just 'example.net' - def self.find_by_name(name) - self.where('name = ?', self.extract_domain_name(name)).first + def self.by_name(name) + self.find_by(name: self.extract_domain_name(name)) end # turns the argument (expected to be a String) into a domain name that is @@ -82,7 +82,7 @@ class Domain < ActiveRecord::Base Noosfero::MultiTenancy.setup!(domainname) @hosting[domainname] ||= begin - domain = Domain.find_by_name(domainname) + domain = Domain.by_name(domainname) !domain.nil? && (domain.owner_type == 'Profile') end end diff --git a/app/models/environment.rb b/app/models/environment.rb index c3503e7..b59dce4 100644 --- a/app/models/environment.rb +++ b/app/models/environment.rb @@ -61,7 +61,7 @@ class Environment < ActiveRecord::Base module Roles def self.admin(env_id) - Role.find_by_key_and_environment_id('environment_administrator', env_id) + Role.find_by(key: 'environment_administrator', environment_id: env_id) end end @@ -248,7 +248,7 @@ class Environment < ActiveRecord::Base acts_as_accessible - has_many :units, :order => 'position' + has_many :units, -> { order 'position' } has_many :production_costs, :as => :owner def superior_intances @@ -714,7 +714,7 @@ class Environment < ActiveRecord::Base def default_hostname(email_hostname = false) domain = 'localhost' unless self.domains(true).empty? - domain = (self.domains.find_by_is_default(true) || self.domains.find(:first, :order => 'id')).name + domain = (self.domains.find_by(is_default: true) || self.domains.order(:id).first).name domain = email_hostname ? domain : (force_www ? ('www.' + domain) : domain) end domain @@ -808,7 +808,7 @@ class Environment < ActiveRecord::Base end def community_default_template - template = Community.find_by_id settings[:community_template_id] + template = Community.find_by id: settings[:community_template_id] template if template && template.is_template? end @@ -821,7 +821,7 @@ class Environment < ActiveRecord::Base end def person_default_template - template = Person.find_by_id settings[:person_template_id] + template = Person.find_by id: settings[:person_template_id] template if template && template.is_template? end @@ -834,7 +834,7 @@ class Environment < ActiveRecord::Base end def enterprise_default_template - template = Enterprise.find_by_id settings[:enterprise_template_id] + template = Enterprise.find_by id: settings[:enterprise_template_id] template if template && template.is_template? end @@ -843,7 +843,7 @@ class Environment < ActiveRecord::Base end def inactive_enterprise_template - template = Enterprise.find_by_id settings[:inactive_enterprise_template_id] + template = Enterprise.find_by id: settings[:inactive_enterprise_template_id] template if template && template.is_template end diff --git a/app/models/forum.rb b/app/models/forum.rb index 464d310..07eb334 100644 --- a/app/models/forum.rb +++ b/app/models/forum.rb @@ -1,6 +1,6 @@ class Forum < Folder - acts_as_having_posts :order => 'updated_at DESC' + acts_as_having_posts -> { reorder 'updated_at DESC' } include PostsLimit attr_accessible :has_terms_of_use, :terms_of_use, :topic_creation @@ -12,7 +12,7 @@ class Forum < Folder before_save do |forum| if forum.has_terms_of_use - last_editor = forum.profile.environment.people.find_by_id(forum.last_changed_by_id) + last_editor = forum.profile.environment.people.find_by(id: forum.last_changed_by_id) if last_editor && !forum.users_with_agreement.exists?(last_editor) forum.users_with_agreement << last_editor end @@ -34,14 +34,14 @@ class Forum < Folder end module TopicCreation - BASE = ActiveSupport::OrderedHash.new + BASE = {} BASE['users'] = _('Logged users') - PERSON = ActiveSupport::OrderedHash.new + PERSON = {} PERSON['self'] = _('Me') PERSON['related'] = _('Friends') - GROUP = ActiveSupport::OrderedHash.new + GROUP = {} GROUP['self'] = _('Administrators') GROUP['related'] = _('Members') diff --git a/app/models/input.rb b/app/models/input.rb index 9bf4546..ba6dfb2 100644 --- a/app/models/input.rb +++ b/app/models/input.rb @@ -9,7 +9,7 @@ class Input < ActiveRecord::Base validates_presence_of :product validates_presence_of :product_category - acts_as_list :scope => :product + acts_as_list scope: -> input { where product_id: input.product_id } belongs_to :unit diff --git a/app/models/invitation.rb b/app/models/invitation.rb index 375562c..c8bf4c5 100644 --- a/app/models/invitation.rb +++ b/app/models/invitation.rb @@ -67,7 +67,7 @@ class Invitation < Task end begin - user = find_by_profile_id ? Person.find_by_id(contact_to_invite).user : User.find_by_email(friend_email) + user = find_by_profile_id ? Person.find_by(id: contact_to_invite).user : User.find_by(email: friend_email) rescue user = nil end diff --git a/app/models/moderate_user_registration.rb b/app/models/moderate_user_registration.rb index 99ea18b..9ade40a 100644 --- a/app/models/moderate_user_registration.rb +++ b/app/models/moderate_user_registration.rb @@ -27,7 +27,7 @@ class ModerateUserRegistration < Task end def perform - user=environment.users.find_by_id(user_id) + user=environment.users.find_by(id: user_id) user.activate end diff --git a/app/models/national_region.rb b/app/models/national_region.rb index ca1b2a0..703d997 100644 --- a/app/models/national_region.rb +++ b/app/models/national_region.rb @@ -27,12 +27,13 @@ class NationalRegion < ActiveRecord::Base :type => NationalRegionType::CITY, :state => state}]; - region = NationalRegion.find(find_return, - :select => "national_regions.name as city, nr.name as state, national_regions.national_region_code", - :conditions => conditions, - :joins => "LEFT JOIN national_regions as nr ON national_regions.parent_national_region_code = nr.national_region_code", - :limit => 10 - ) + region = NationalRegion + .select('national_regions.name as city, nr.name as state, national_regions.national_region_code') + .where(conditions) + .joins('LEFT JOIN national_regions as nr ON national_regions.parent_national_region_code = nr.national_region_code') + .limit(10) + region = region.send find_return + return region end @@ -50,19 +51,19 @@ class NationalRegion < ActiveRecord::Base {:name => state_name, :type => NationalRegionType::STATE}]; - region = NationalRegion.find(find_return, - :select => "national_regions.name as state, national_regions.national_region_code", - :conditions => conditions, - :limit => 10 - ) + region = NationalRegion + .select('national_regions.name as state, national_regions.national_region_code') + .where(conditions) + .limit(10) + region = region.send find_return + return region end def self.validate!(city, state, country) - country_region = NationalRegion.find_by_national_region_code(country, - :conditions => ["national_region_type_id = :type", - {:type => NationalRegionType::COUNTRY}]) + country_region = NationalRegion + .find_by(national_region_code: country, national_region_type_id: NationalRegionType::COUNTRY) if(country_region) diff --git a/app/models/organization.rb b/app/models/organization.rb index 190d253..220b30d 100644 --- a/app/models/organization.rb +++ b/app/models/organization.rb @@ -55,7 +55,7 @@ class Organization < Profile has_many :custom_roles, :class_name => 'Role', :foreign_key => :profile_id - scope :more_popular, :order => 'members_count DESC' + scope :more_popular, -> { order 'members_count DESC' } validate :presence_of_required_fieds, :unless => :is_template diff --git a/app/models/person.rb b/app/models/person.rb index 54297df..ff8bd41 100644 --- a/app/models/person.rb +++ b/app/models/person.rb @@ -109,7 +109,8 @@ class Person < Profile has_and_belongs_to_many :acepted_forums, :class_name => 'Forum', :join_table => 'terms_forum_people' has_and_belongs_to_many :articles_with_access, :class_name => 'Article', :join_table => 'article_privacy_exceptions' - has_many :suggested_profiles, class_name: 'ProfileSuggestion', foreign_key: :person_id, order: 'score DESC', dependent: :destroy + has_many :suggested_profiles, -> { order 'score DESC' }, + class_name: 'ProfileSuggestion', foreign_key: :person_id, dependent: :destroy has_many :suggested_people, -> { where 'profile_suggestions.suggestion_type = ? AND profile_suggestions.enabled = ?', 'Person', true }, through: :suggested_profiles, source: :suggestion @@ -392,7 +393,7 @@ class Person < Profile def self.with_pending_tasks - Person.find(:all).select{ |person| !person.tasks.pending.empty? or person.has_organization_pending_tasks? } + Person.all.select{ |person| !person.tasks.pending.empty? or person.has_organization_pending_tasks? } end def has_organization_pending_tasks? @@ -486,7 +487,7 @@ class Person < Profile end def each_friend(offset=0) - while friend = self.friends.first(:order => :id, :offset => offset) + while friend = self.friends.order(:id).offset(offset).first yield friend offset = offset + 1 end @@ -568,7 +569,7 @@ class Person < Profile end def remove_suggestion(profile) - suggestion = suggested_profiles.find_by_suggestion_id profile.id + suggestion = suggested_profiles.find_by suggestion_id: profile.id suggestion.disable if suggestion end diff --git a/app/models/product.rb b/app/models/product.rb index 0d1f1c5..e47610b 100644 --- a/app/models/product.rb +++ b/app/models/product.rb @@ -28,7 +28,7 @@ class Product < ActiveRecord::Base belongs_to :product_category - has_many :inputs, :dependent => :destroy, :order => 'position' + has_many :inputs, -> { order 'position' }, dependent: :destroy has_many :price_details, :dependent => :destroy has_many :production_costs, :through => :price_details @@ -50,7 +50,7 @@ class Product < ActiveRecord::Base validates_numericality_of :price, :allow_nil => true validates_numericality_of :discount, :allow_nil => true - scope :more_recent, :order => "created_at DESC" + scope :more_recent, -> { order 'created_at DESC' } scope :from_category, -> category { joins(:product_category).where('categories.path LIKE ?', "%#{category.slug}%") if category @@ -75,6 +75,8 @@ class Product < ActiveRecord::Base ).uniq } + scope :recent, -> limit=nil { order('id DESC').limit(limit) } + after_update :save_image def lat @@ -128,10 +130,6 @@ class Product < ActiveRecord::Base product_category ? product_category.name : _('Uncategorized product') end - def self.recent(limit = nil) - self.find(:all, :order => 'id desc', :limit => limit) - end - def url self.profile.public_profile_url.merge(:controller => 'manage_products', :action => 'show', :id => id) end diff --git a/app/models/product_category.rb b/app/models/product_category.rb index 8aa37da..e1bccd5 100644 --- a/app/models/product_category.rb +++ b/app/models/product_category.rb @@ -5,7 +5,7 @@ class ProductCategory < Category attr_accessible :name, :parent, :environment - scope :unique, :select => 'DISTINCT ON (path) categories.*' + scope :unique, -> { select 'DISTINCT ON (path) categories.*' } scope :by_enterprise, -> enterprise { distinct.joins(:products). where('products.profile_id = ?', enterprise.id) diff --git a/app/models/profile.rb b/app/models/profile.rb index ebc22ee..d99354a 100644 --- a/app/models/profile.rb +++ b/app/models/profile.rb @@ -62,7 +62,7 @@ class Profile < ActiveRecord::Base end private def self.find_role(name, env_id) - ::Role.find_by_key_and_environment_id("profile_#{name}", env_id) + ::Role.find_by key: "profile_#{name}", environment_id: env_id end end @@ -115,6 +115,9 @@ class Profile < ActiveRecord::Base } scope :no_templates, -> { where is_template: false } + scope :recent, -> limit=nil { order('id DESC').limit(limit) } + + # Returns a scoped object to select profiles in a given location or in a radius # distance from the given location center. # The parameter can be the `request.params` with the keys: @@ -178,14 +181,6 @@ class Profile < ActiveRecord::Base members(field).where("LOWER(#{field}) LIKE ?", "%#{value.downcase}%") if value end - class << self - def count_with_distinct(*args) - options = args.last || {} - count_without_distinct(:id, {:distinct => true}.merge(options)) - end - alias_method_chain :count, :distinct - end - def members_by_role(roles) Person.members_of(self).by_role(roles) end @@ -203,18 +198,17 @@ class Profile < ActiveRecord::Base scope :is_public, -> { where visible: true, public_profile: true, secret: false } scope :enabled, -> { where enabled: true } - # Subclasses must override this method - scope :more_popular - - scope :more_active, :order => 'activities_count DESC' - scope :more_recent, :order => "created_at DESC" + # subclass specific + scope :more_popular, -> { } + scope :more_active, -> { order 'activities_count DESC' } + scope :more_recent, -> { order "created_at DESC" } acts_as_trackable :dependent => :destroy has_many :profile_activities has_many :action_tracker_notifications, :foreign_key => 'profile_id' - has_many :tracked_notifications, :through => :action_tracker_notifications, :source => :action_tracker, :order => 'updated_at DESC' - has_many :scraps_received, :class_name => 'Scrap', :foreign_key => :receiver_id, :order => "updated_at DESC", :dependent => :destroy + has_many :tracked_notifications, -> { order 'updated_at DESC' }, through: :action_tracker_notifications, source: :action_tracker + has_many :scraps_received, -> { order 'updated_at DESC' }, class_name: 'Scrap', foreign_key: :receiver_id, dependent: :destroy belongs_to :template, :class_name => 'Profile', :foreign_key => 'template_id' has_many :comments_received, :class_name => 'Comment', :through => :articles, :source => :comments @@ -295,7 +289,7 @@ class Profile < ActiveRecord::Base has_many :tasks, :dependent => :destroy, :as => 'target' - has_many :events, :source => 'articles', :class_name => 'Event', :order => 'start_date' + has_many :events, -> { order 'start_date' }, source: 'articles', class_name: 'Event' def find_in_all_tasks(task_id) begin @@ -559,7 +553,7 @@ class Profile < ActiveRecord::Base # person = Profile['username'] # org = Profile.['orgname'] def [](identifier) - self.find_by_identifier(identifier) + self.find_by identifier: identifier end end @@ -738,11 +732,11 @@ private :generate_url, :url_options def copy_article_tree(article, parent=nil) return if !copy_article?(article) - original_article = self.articles.find_by_name(article.name) + original_article = self.articles.find_by name: article.name if original_article num = 2 new_name = original_article.name + ' ' + num.to_s - while self.articles.find_by_name(new_name) + while self.articles.find_by name: new_name num = num + 1 new_name = original_article.name + ' ' + num.to_s end @@ -799,10 +793,6 @@ private :generate_url, :url_options end end - def self.recent(limit = nil) - self.find(:all, :order => 'id desc', :limit => limit) - end - # returns +true+ if the given +user+ can see profile information about this # +profile+, and +false+ otherwise. def display_info_to?(user) @@ -896,7 +886,7 @@ private :generate_url, :url_options has_many :blogs, :source => 'articles', :class_name => 'Blog' def blog - self.has_blog? ? self.blogs.first(:order => 'id') : nil + self.has_blog? ? self.blogs.order(:id).first : nil end def has_blog? @@ -906,7 +896,7 @@ private :generate_url, :url_options has_many :forums, :source => 'articles', :class_name => 'Forum' def forum - self.has_forum? ? self.forums.first(:order => 'id') : nil + self.has_forum? ? self.forums.order(:id).first : nil end def has_forum? @@ -1134,7 +1124,7 @@ private :generate_url, :url_options settings_items :custom_url_redirection, type: String, default: nil def remove_from_suggestion_list(person) - suggestion = person.suggested_profiles.find_by_suggestion_id self.id + suggestion = person.suggested_profiles.find_by suggestion_id: self.id suggestion.disable if suggestion end diff --git a/app/models/profile_activity.rb b/app/models/profile_activity.rb index 1eadeb3..8d87fb0 100644 --- a/app/models/profile_activity.rb +++ b/app/models/profile_activity.rb @@ -9,8 +9,12 @@ class ProfileActivity < ActiveRecord::Base belongs_to :activity, polymorphic: true # non polymorphic versions - belongs_to :scrap, foreign_key: :activity_id, class_name: 'Scrap', conditions: {profile_activities: {activity_type: 'Scrap'}} - belongs_to :action_tracker, foreign_key: :activity_id, class_name: 'ActionTracker::Record', conditions: {profile_activities: {activity_type: 'ActionTracker::Record'}} + belongs_to :scrap, -> { + where profile_activities: {activity_type: 'Scrap'} + }, foreign_key: :activity_id, class_name: 'Scrap' + belongs_to :action_tracker, -> { + where profile_activities: {activity_type: 'ActionTracker::Record'} + }, foreign_key: :activity_id, class_name: 'ActionTracker::Record' before_validation :copy_timestamps diff --git a/app/models/profile_list_block.rb b/app/models/profile_list_block.rb index 6357776..4bf02ff 100644 --- a/app/models/profile_list_block.rb +++ b/app/models/profile_list_block.rb @@ -18,11 +18,11 @@ class ProfileListBlock < Block result = nil public_profiles = profiles.is_public.includes([:image,:domains,:preferred_domain,:environment]) if !prioritize_profiles_with_image -result = public_profiles.all(:limit => get_limit, :order => 'profiles.updated_at DESC').sort_by{ rand } + result = public_profiles.limit(get_limit).order('profiles.updated_at DESC').sort_by{ rand } elsif profiles.visible.with_image.count >= get_limit - result = public_profiles.with_image.all(:limit => get_limit * 5, :order => 'profiles.updated_at DESC').sort_by{ rand } + result = public_profiles.with_image.limit(get_limit * 5).order('profiles.updated_at DESC').sort_by{ rand } else - result = public_profiles.with_image.sort_by{ rand } + public_profiles.without_image.all(:limit => get_limit * 5, :order => 'profiles.updated_at DESC').sort_by{ rand } + result = public_profiles.with_image.sort_by{ rand } + public_profiles.without_image.limit(get_limit * 5).order('profiles.updated_at DESC').sort_by{ rand } end result.slice(0..get_limit-1) end diff --git a/app/models/profile_suggestion.rb b/app/models/profile_suggestion.rb index 54e7b41..41ee7ce 100644 --- a/app/models/profile_suggestion.rb +++ b/app/models/profile_suggestion.rb @@ -120,7 +120,8 @@ class ProfileSuggestion < ActiveRecord::Base return if suggested_profiles.blank? suggested_profiles.each do |suggested_profile| - suggestion = person.suggested_profiles.find_or_initialize_by_suggestion_id(suggested_profile.id) + suggestion = person.suggested_profiles.find_by suggestion_id: suggested_profile.id + suggestion ||= person.suggested_profiles.build({suggestion_id: suggested_profile.id}, without_protection: true) RULES.each do |rule, options| begin value = suggested_profile.send("#{rule}_count").to_i diff --git a/app/models/region.rb b/app/models/region.rb index 3475da4..36e7128 100644 --- a/app/models/region.rb +++ b/app/models/region.rb @@ -1,8 +1,8 @@ -# Region is a special type of category that is related to geographical issues. +# Region is a special type of category that is related to geographical issues. class Region < Category - - attr_accessible :name - + + attr_accessible :name + has_and_belongs_to_many :validators, :class_name => 'Organization', :join_table => :region_validators require_dependency 'enterprise' # enterprises can also be validators @@ -11,8 +11,10 @@ class Region < Category validators.count > 0 end - scope :with_validators, :select => 'DISTINCT ON (categories.id) *', - :joins => 'INNER JOIN region_validators on (region_validators.region_id = categories.id)' + scope :with_validators, -> { + select('DISTINCT ON (categories.id) *') + .joins('INNER JOIN region_validators on (region_validators.region_id = categories.id)') + } end diff --git a/app/models/scrap.rb b/app/models/scrap.rb index cabcc2d..3e5a60c 100644 --- a/app/models/scrap.rb +++ b/app/models/scrap.rb @@ -13,7 +13,9 @@ class Scrap < ActiveRecord::Base has_many :replies, :class_name => 'Scrap', :foreign_key => 'scrap_id', :dependent => :destroy belongs_to :root, :class_name => 'Scrap', :foreign_key => 'scrap_id' - has_many :profile_activities, foreign_key: :activity_id, conditions: {profile_activities: {activity_type: 'Scrap'}}, dependent: :destroy + has_many :profile_activities, -> { + where profile_activities: {activity_type: 'Scrap'} + }, foreign_key: :activity_id, dependent: :destroy after_create :create_activity after_update :update_activity diff --git a/app/models/search_term.rb b/app/models/search_term.rb index d6720ac..2b62c74 100644 --- a/app/models/search_term.rb +++ b/app/models/search_term.rb @@ -25,7 +25,7 @@ class SearchTerm < ActiveRecord::Base # Therefore the score is 97. Them we sum every score to get the total score # for a search term. def self.occurrences_scores - ActiveSupport::OrderedHash[*ActiveRecord::Base.connection.execute( + Hash[*ActiveRecord::Base.connection.execute( joins(:occurrences). select("search_terms.id, sum(#{SearchTermOccurrence::EXPIRATION_TIME.to_i} - extract(epoch from (now() - search_term_occurrences.created_at))) as value"). where("search_term_occurrences.created_at > ?", DateTime.now - SearchTermOccurrence::EXPIRATION_TIME). diff --git a/app/models/task.rb b/app/models/task.rb index 6db5183..cd867fa 100644 --- a/app/models/task.rb +++ b/app/models/task.rb @@ -137,9 +137,9 @@ class Task < ActiveRecord::Base group = klass.to_s.downcase.pluralize id = attribute.to_s + "_id" if environment.respond_to?(group) - attrb = value || environment.send(group).find_by_id(record.send(id)) + attrb = value || environment.send(group).find_by(id: record.send(id)) else - attrb = value || klass.find_by_id(record.send(id)) + attrb = value || klass.find_by(id: record.send(id)) end if attrb.respond_to?(klass.to_s.downcase + "?") unless attrb.send(klass.to_s.downcase + "?") diff --git a/app/models/unit.rb b/app/models/unit.rb index 31ecd1b..5faaa01 100644 --- a/app/models/unit.rb +++ b/app/models/unit.rb @@ -1,13 +1,17 @@ class Unit < ActiveRecord::Base + acts_as_list scope: -> unit { where environment_id: unit.environment_id } + attr_accessible :name, :singular, :plural, :environment validates_presence_of :singular validates_presence_of :plural belongs_to :environment + validates_presence_of :environment_id - acts_as_list :scope => :environment + validates_presence_of :singular + validates_presence_of :plural def name self.singular diff --git a/app/models/user.rb b/app/models/user.rb index a96a7a4..1eff6aa 100644 --- a/app/models/user.rb +++ b/app/models/user.rb @@ -25,7 +25,7 @@ class User < ActiveRecord::Base end def self.[](login) - self.find_by_login(login) + self.find_by login: login end # FIXME ugly workaround diff --git a/app/views/layouts/_user.html.erb b/app/views/layouts/_user.html.erb index cec9a5d..cabfc06 100644 --- a/app/views/layouts/_user.html.erb +++ b/app/views/layouts/_user.html.erb @@ -1,5 +1,5 @@
- <% user = (session[:user] && User.find_by_id(session[:user])) || nil %> + <% user = (session[:user] && User.find_by(id: session[:user])) || nil %> <% if user.present? %> <% user = user.person %> diff --git a/app/views/shared/_list_groups.html.erb b/app/views/shared/_list_groups.html.erb index 05466a7..6db4709 100644 --- a/app/views/shared/_list_groups.html.erb +++ b/app/views/shared/_list_groups.html.erb @@ -6,7 +6,7 @@
<%= group.name %>
- <%= _('Role: %s') % rolename_for(profile, group) + '
' if profile.role_assignments.find_by_resource_id(group.id) %> + <%= _('Role: %s') % rolename_for(profile, group) + '
' if profile.role_assignments.find_by(resource_id: group.id) %> <%= _('Type: %s') % _(group.class.identification) %>
<%= _('Description: %s') % group.description + '
' if group.community? %> <%= _('Members: %s') % group.members_count.to_s %>
diff --git a/app/views/spam/_suggest_article.html.erb b/app/views/spam/_suggest_article.html.erb index 9e99760..d139852 100644 --- a/app/views/spam/_suggest_article.html.erb +++ b/app/views/spam/_suggest_article.html.erb @@ -9,7 +9,7 @@
  • <%=_('Email')%>: <%=task.email%>
  • <%=_('Source')%>: <%=task.article_object.source_name%>
  • <%=_('Source URL')%>: <%=task.article_object.source%>
  • -
  • <%=_('Folder')%>: <%=(a = Article.find_by_id(task.article_object.parent_id))?a.name : '' + s_('Folder|none') + ''%>
  • +
  • <%=_('Folder')%>: <%=if (a = Article.find_by(id: task.article_object.parent_id)) then a.name else '' + s_('Folder|none') + '' end%>
  • <%=_('Lead')%>: <%=task.article_object.abstract.blank? ? '' + s_('Abstract|empty') + '' : task.article_object.abstract%>
  • <%=_('Body')%>:
    diff --git a/db/migrate/033_destroy_organization_and_person_infos.rb b/db/migrate/033_destroy_organization_and_person_infos.rb index 27a2994..dbd29e8 100644 --- a/db/migrate/033_destroy_organization_and_person_infos.rb +++ b/db/migrate/033_destroy_organization_and_person_infos.rb @@ -1,6 +1,6 @@ class DestroyOrganizationAndPersonInfos < ActiveRecord::Migration def self.up - Person.find(:all).each do |i| + Person.find_each do |i| info = ActiveRecord::Base.connection.select_one("select * from person_infos where person_id = #{i.id}") i.name = info["name"] unless info["name"].nil? i.address = info["address"] unless info["address"].nil? @@ -11,7 +11,7 @@ class DestroyOrganizationAndPersonInfos < ActiveRecord::Migration end drop_table :person_infos - Organization.find(:all).each do |i| + Organization.find_each do |i| info = ActiveRecord::Base.connection.select_one("select * from organization_infos where organization_id = #{i.id}") [ "contact_person", "contact_email", "acronym", "foundation_year", "legal_form", "economic_activity", "management_information", "validated" ].each do |field| i.send("#{field}=", info[field]) diff --git a/db/migrate/043_add_virtual_flag_to_categorizations.rb b/db/migrate/043_add_virtual_flag_to_categorizations.rb index f9baa79..942890d 100644 --- a/db/migrate/043_add_virtual_flag_to_categorizations.rb +++ b/db/migrate/043_add_virtual_flag_to_categorizations.rb @@ -2,13 +2,13 @@ class AddVirtualFlagToCategorizations < ActiveRecord::Migration def self.up add_column :articles_categories, :virtual, :boolean, :default => false execute('update articles_categories set virtual = (1!=1)') - Article.find(:all).each do |article| + Article.find_each do |article| article.category_ids = article.categories.map(&:id) end add_column :categories_profiles, :virtual, :boolean, :default => false execute('update categories_profiles set virtual = (1!=1)') - Profile.find(:all).each do |profile| + Profile.find_each do |profile| profile.category_ids = profile.categories.map(&:id) end end diff --git a/db/migrate/044_create_product_categorizations.rb b/db/migrate/044_create_product_categorizations.rb index 827d4c1..981885a 100644 --- a/db/migrate/044_create_product_categorizations.rb +++ b/db/migrate/044_create_product_categorizations.rb @@ -1,6 +1,6 @@ class CreateProductCategorizations < ActiveRecord::Migration def self.up - + create_table :product_categorizations do |t| t.integer :category_id t.integer :product_id @@ -11,7 +11,7 @@ class CreateProductCategorizations < ActiveRecord::Migration total = Product.count.to_f percent = 0 - Product.find(:all).each_with_index do |p,i| + Product.find_each_with_index do |p,i| if p.product_category ProductCategorization.add_category_to_product(p.product_category, p) end diff --git a/db/migrate/052_create_templates.rb b/db/migrate/052_create_templates.rb index cd4209a..fc0f11b 100644 --- a/db/migrate/052_create_templates.rb +++ b/db/migrate/052_create_templates.rb @@ -1,6 +1,6 @@ class CreateTemplates < ActiveRecord::Migration def self.up - Environment.find(:all).each do |env| + Environment.find_each do |env| if env.person_template.nil? && env.community_template.nil? && env.enterprise_template.nil? env.create_templates end diff --git a/db/migrate/069_add_enviroment_id_to_role.rb b/db/migrate/069_add_enviroment_id_to_role.rb index 9cf8c3b..1989858 100644 --- a/db/migrate/069_add_enviroment_id_to_role.rb +++ b/db/migrate/069_add_enviroment_id_to_role.rb @@ -12,13 +12,13 @@ class AddEnviromentIdToRole < ActiveRecord::Migration def self.up add_column :roles, :environment_id, :integer - roles = Role.find(:all) - Environment.find(:all).each do |env| + roles = Role.all + Environment.find_each do |env| roles.each do |role| re = RoleWithEnvironment.new(role.attributes) re.environment = env re.save - RoleAssignment.find_all_by_role_id(role.id).select{|ra| ra.resource && (ra.resource.kind_of?(Profile) ? ra.resource.environment_id : ra.resource.id) == env.id }.each do |ra| + RoleAssignment.where(role_id: role.id).select{|ra| ra.resource && (ra.resource.kind_of?(Profile) ? ra.resource.environment_id : ra.resource.id) == env.id }.each do |ra| ra.role_id = re.id ra.save end @@ -30,14 +30,14 @@ class AddEnviromentIdToRole < ActiveRecord::Migration def self.down roles_by_name = {} roles_by_key = {} - roles_with_environment = RoleWithEnvironment.find(:all) + roles_with_environment = RoleWithEnvironment.all roles_with_environment.each do |re| if re.key role = roles_by_name[re.key] || roles_by_key[re.name] || Role.create(re.attributes) roles_by_name[role.name] ||= roles_by_key[role.key] ||= role end role = roles_by_name[re.name] ||= Role.create(re.attributes) unless role - RoleAssignment.find_all_by_role_id(re.id).each do |ra| + RoleAssignment.where(role_id: re.id).each do |ra| ra.role_id = role.id ra.save end diff --git a/db/migrate/20100413231206_strip_html_from_tag_names.rb b/db/migrate/20100413231206_strip_html_from_tag_names.rb index cee1176..14a836a 100644 --- a/db/migrate/20100413231206_strip_html_from_tag_names.rb +++ b/db/migrate/20100413231206_strip_html_from_tag_names.rb @@ -1,6 +1,6 @@ class StripHtmlFromTagNames < ActiveRecord::Migration def self.up - Tag.all(:conditions => "name LIKE '%<%' OR name LIKE '%>%'").each do |tag| + Tag.where("name LIKE '%<%' OR name LIKE '%>%'").find_each do |tag| tag.name = tag.name.gsub(/[<>]/, '') tag.save end diff --git a/db/migrate/20100621235235_set_product_category_id_to_products.rb b/db/migrate/20100621235235_set_product_category_id_to_products.rb index 614172f..ffb76cf 100644 --- a/db/migrate/20100621235235_set_product_category_id_to_products.rb +++ b/db/migrate/20100621235235_set_product_category_id_to_products.rb @@ -1,6 +1,6 @@ class SetProductCategoryIdToProducts < ActiveRecord::Migration def self.up - Product.all(:conditions => { :product_category_id => nil }).each do |product| + Product.where(product_category_id: nil).find_each do |product| next if product.enterprise.nil? product.update_attribute(:product_category_id, ProductCategory.top_level_for(product.enterprise.environment).first.id) end diff --git a/db/migrate/20100730141134_set_owner_environment_to_enterprises_environment.rb b/db/migrate/20100730141134_set_owner_environment_to_enterprises_environment.rb index 625be71..d3fbab5 100644 --- a/db/migrate/20100730141134_set_owner_environment_to_enterprises_environment.rb +++ b/db/migrate/20100730141134_set_owner_environment_to_enterprises_environment.rb @@ -1,7 +1,7 @@ class SetOwnerEnvironmentToEnterprisesEnvironment < ActiveRecord::Migration def self.up - CreateEnterprise.find_all_by_status(3).each do |t| - if(Enterprise.find_by_identifier(t.data[:identifier])) + CreateEnterprise.where(status: 3).each do |t| + if(Enterprise.find_by(identifier: t.data[:identifier])) update("UPDATE profiles SET environment_id = '%s' WHERE identifier = '%s'" % [Person.find(t.requestor_id).environment.id, t.data[:identifier]]) end diff --git a/db/migrate/20100809044243_dont_accept_null_to_environment_theme.rb b/db/migrate/20100809044243_dont_accept_null_to_environment_theme.rb index 84b9f7b..1bb9864 100644 --- a/db/migrate/20100809044243_dont_accept_null_to_environment_theme.rb +++ b/db/migrate/20100809044243_dont_accept_null_to_environment_theme.rb @@ -1,6 +1,6 @@ class DontAcceptNullToEnvironmentTheme < ActiveRecord::Migration def self.up - Environment.all(:conditions => {:theme => nil}).each do |environment| + Environment.where(theme: nil).find_each do |environment| environment.update_attribute(:theme, 'default') end @@ -10,7 +10,7 @@ class DontAcceptNullToEnvironmentTheme < ActiveRecord::Migration def self.down change_column :environments, :theme, :string, :default => nil, :null => true - Environment.all(:conditions => {:theme => 'default'}).each do |environment| + Environment.where(theme: 'default').find_each do |environment| environment.update_attribute(:theme, nil) end end diff --git a/db/migrate/20100920182433_change_action_tracker_record.rb b/db/migrate/20100920182433_change_action_tracker_record.rb index 27774d4..84efa58 100644 --- a/db/migrate/20100920182433_change_action_tracker_record.rb +++ b/db/migrate/20100920182433_change_action_tracker_record.rb @@ -2,7 +2,7 @@ class ChangeActionTrackerRecord < ActiveRecord::Migration def self.up rename_column(:action_tracker, :dispatcher_type, :target_type) rename_column(:action_tracker, :dispatcher_id, :target_id) - ActionTracker::Record.update_all("verb='create_article'", {:verb => 'publish_article_in_community'}) + ActionTracker:Record.where(verb: 'publish_article_in_community').update_all verb: 'create_article' end def self.down diff --git a/db/migrate/20111228202739_remove_useless_tracked_actions.rb b/db/migrate/20111228202739_remove_useless_tracked_actions.rb index 5da8b0e..afc2662 100644 --- a/db/migrate/20111228202739_remove_useless_tracked_actions.rb +++ b/db/migrate/20111228202739_remove_useless_tracked_actions.rb @@ -2,7 +2,7 @@ class RemoveUselessTrackedActions < ActiveRecord::Migration def self.up select_all("SELECT id FROM action_tracker").each do |tracker| verbs = ['update_article', 'remove_article', 'leave_comment', 'leave_community', 'remove_member_in_community'] - activity = ActionTracker::Record.find_by_id(tracker['id']) + activity = ActionTracker::Record.find_by(id: tracker['id']) if activity if (activity.updated_at.to_time < Time.now.months_ago(3)) || verbs.include?(activity.verb) activity.destroy diff --git a/db/migrate/20120228202739_adapt_create_articles_activity.rb b/db/migrate/20120228202739_adapt_create_articles_activity.rb index 0c77469..3d8a6e8 100644 --- a/db/migrate/20120228202739_adapt_create_articles_activity.rb +++ b/db/migrate/20120228202739_adapt_create_articles_activity.rb @@ -4,7 +4,7 @@ class AdaptCreateArticlesActivity < ActiveRecord::Migration # Creating new activities only to recent articles (not grouping) def self.up select_all("SELECT id FROM action_tracker WHERE verb = 'create_article'").each do |tracker| - activity = ActionTracker::Record.find_by_id(tracker['id']) + activity = ActionTracker::Record.find_by(id: tracker['id']) if activity activity.destroy end diff --git a/db/migrate/20120718162001_create_default_licenses.rb b/db/migrate/20120718162001_create_default_licenses.rb index c911932..85c7889 100644 --- a/db/migrate/20120718162001_create_default_licenses.rb +++ b/db/migrate/20120718162001_create_default_licenses.rb @@ -14,14 +14,14 @@ class CreateDefaultLicenses < ActiveRecord::Migration def self.down licenses = [] - licenses += License.find(:all, :conditions => {:name => 'CC (by)'}) - licenses += License.find(:all, :conditions => {:name => 'CC (by-nd)'}) - licenses += License.find(:all, :conditions => {:name => 'CC (by-sa)'}) - licenses += License.find(:all, :conditions => {:name => 'CC (by-nc)'}) - licenses += License.find(:all, :conditions => {:name => 'CC (by-nc-nd)'}) - licenses += License.find(:all, :conditions => {:name => 'CC (by-nc-sa)'}) - licenses += License.find(:all, :conditions => {:name => 'Free Art'}) - licenses += License.find(:all, :conditions => {:name => 'GNU FDL'}) + licenses += License.where name: 'CC (by)' + licenses += License.where name: 'CC (by-nd)' + licenses += License.where name: 'CC (by-sa)' + licenses += License.where name: 'CC (by-nc)' + licenses += License.where name: 'CC (by-nc-nd)' + licenses += License.where name: 'CC (by-nc-sa)' + licenses += License.where name: 'Free Art' + licenses += License.where name: 'GNU FDL' licenses.compact.map(&:destroy) end end diff --git a/db/migrate/20120818030329_remove_action_tracker_with_target_nil.rb b/db/migrate/20120818030329_remove_action_tracker_with_target_nil.rb index 946d8d0..7ea09a3 100644 --- a/db/migrate/20120818030329_remove_action_tracker_with_target_nil.rb +++ b/db/migrate/20120818030329_remove_action_tracker_with_target_nil.rb @@ -1,7 +1,7 @@ class RemoveActionTrackerWithTargetNil < ActiveRecord::Migration def self.up select_all("SELECT id FROM action_tracker").each do |tracker| - activity = ActionTracker::Record.find_by_id(tracker['id']) + activity = ActionTracker::Record.find_by(id: tracker['id']) if activity && activity.target.nil? activity.destroy end diff --git a/db/migrate/20140221142304_move_title_virtual_field_to_name_in_uploaded_file.rb b/db/migrate/20140221142304_move_title_virtual_field_to_name_in_uploaded_file.rb index 84e1616..0d05d67 100644 --- a/db/migrate/20140221142304_move_title_virtual_field_to_name_in_uploaded_file.rb +++ b/db/migrate/20140221142304_move_title_virtual_field_to_name_in_uploaded_file.rb @@ -2,8 +2,8 @@ class MoveTitleVirtualFieldToNameInUploadedFile < ActiveRecord::Migration def self.up UploadedFile.find_each do |uploaded_file| uploaded_file.name = uploaded_file.setting.delete(:title) - UploadedFile.update_all({:setting => uploaded_file.setting.to_yaml, :name => uploaded_file.name}, - "id = #{uploaded_file.id}") + UploadedFile.where(id: uploaded_file.id).update_all setting: uploaded_file.setting.to_yaml, name: uploaded_file.name + end end diff --git a/db/migrate/20140807134625_change_category_display_color_to_string.rb b/db/migrate/20140807134625_change_category_display_color_to_string.rb index f43a635..7fa8905 100644 --- a/db/migrate/20140807134625_change_category_display_color_to_string.rb +++ b/db/migrate/20140807134625_change_category_display_color_to_string.rb @@ -8,7 +8,7 @@ class ChangeCategoryDisplayColorToString < ActiveRecord::Migration end COLORS.each_with_index do |color, i| - Category.update_all({:display_color_tmp => color}, {:display_color => i+1}) + Category.where(display_color: i+1).update_all display_color_tmp: color end change_table :categories do |t| @@ -25,7 +25,7 @@ class ChangeCategoryDisplayColorToString < ActiveRecord::Migration end COLORS.each_with_index do |color, i| - Category.update_all({:display_color_tmp => i+1}, {:display_color => color}) + Category.where(display_color: color).update_all display_color_tmp: i+1 end change_table :categories do |t| diff --git a/db/migrate/20150210143723_add_custom_roles_permission_to_admin_roles.rb b/db/migrate/20150210143723_add_custom_roles_permission_to_admin_roles.rb index b2ad9b0..7e3d3d6 100644 --- a/db/migrate/20150210143723_add_custom_roles_permission_to_admin_roles.rb +++ b/db/migrate/20150210143723_add_custom_roles_permission_to_admin_roles.rb @@ -1,15 +1,15 @@ class AddCustomRolesPermissionToAdminRoles < ActiveRecord::Migration def self.up - environment_admin = Role.find_by_key("environment_administrator") - profile_admin = Role.find_by_key("profile_admin") + environment_admin = Role.find_by(key: "environment_administrator") + profile_admin = Role.find_by(key: "profile_admin") environment_admin.permissions.append("manage_custom_roles") profile_admin.permissions.append("manage_custom_roles") environment_admin.save! profile_admin.save! end def self.down - environment_admin = Role.find_by_key("environment_administrator") - profile_admin = Role.find_by_key("profile_admin") + environment_admin = Role.find_by(key: "environment_administrator") + profile_admin = Role.find_by(key: "profile_admin") environment_admin.permissions.delete("manage_custom_roles") profile_admin.permissions.delete("manage_custom_roles") environment_admin.save! diff --git a/debian/control b/debian/control index d065c3b..dca1d5a 100644 --- a/debian/control +++ b/debian/control @@ -45,7 +45,6 @@ Depends: adduser, ruby-actionpack-action-caching, ruby-actionpack-page-caching, ruby-activerecord-session-store, - ruby-activerecord-deprecated-finders, ruby-acts-as-taggable-on (>= 3.5), ruby-api-pagination, ruby-daemons, diff --git a/features/step_definitions/activate_enterprise_steps.rb b/features/step_definitions/activate_enterprise_steps.rb index 83b7e3b..90eb54f 100644 --- a/features/step_definitions/activate_enterprise_steps.rb +++ b/features/step_definitions/activate_enterprise_steps.rb @@ -1,15 +1,15 @@ Given /^I fill in "([^\"]*)" with code of "([^\"]*)"$/ do |field, enterprise| - enterprise = Enterprise.find_by_name(enterprise) + enterprise = Enterprise.find_by(name: enterprise) value = EnterpriseActivation.all.select { |task| task.enterprise == enterprise}.first.code fill_in(field, :with => value) end Given /^enterprise "([^\"]*)" should be enabled$/ do |enterprise| - Enterprise.find_by_name(enterprise).enabled?.should be_truthy + Enterprise.find_by(name: enterprise).enabled?.should be_truthy end Given /^"([^\"]*)" is the active enterprise template$/ do |enterprise| - template = Enterprise.find_by_name(enterprise) + template = Enterprise.find_by(name: enterprise) template.boxes.destroy_all template.boxes << Box.new template.layout_template = 'leftbar' @@ -24,8 +24,8 @@ Given /^"([^\"]*)" is the active enterprise template$/ do |enterprise| end Given /^"([^\"]*)" has "([^\"]*)" as template$/ do |ent, templ| - template = Enterprise.find_by_name(templ) - enterprise = Enterprise.find_by_name(ent) + template = Enterprise.find_by(name: templ) + enterprise = Enterprise.find_by(name: ent) (template.boxes.size == enterprise.boxes.size).should be_truthy (template.layout_template == enterprise.layout_template).should be_truthy (template.theme == enterprise.theme).should be_truthy @@ -34,8 +34,8 @@ Given /^"([^\"]*)" has "([^\"]*)" as template$/ do |ent, templ| end Given /^"([^\"]*)" doesnt have "([^\"]*)" as template$/ do |ent, templ| - template = Enterprise.find_by_name(templ) - enterprise = Enterprise.find_by_name(ent) + template = Enterprise.find_by(name: templ) + enterprise = Enterprise.find_by(name: ent) (template.boxes.size == enterprise.boxes.size).should be_falsey (template.layout_template == enterprise.layout_template).should be_falsey (template.theme == enterprise.theme).should be_falsey @@ -44,16 +44,16 @@ Given /^"([^\"]*)" doesnt have "([^\"]*)" as template$/ do |ent, templ| end Given /^enterprise "([^\"]*)" is enabled$/ do |enterprise| - Enterprise.find_by_name(enterprise).update_attribute(:enabled,true) - Enterprise.find_by_name(enterprise).enabled?.should be_truthy + Enterprise.find_by(name: enterprise).update_attribute(:enabled,true) + Enterprise.find_by(name: enterprise).enabled?.should be_truthy end Given /^enterprise "([^\"]*)" should be blocked$/ do |enterprise| - Enterprise.find_by_name(enterprise).blocked?.should be_truthy + Enterprise.find_by(name: enterprise).blocked?.should be_truthy end Given /^enterprise "([^\"]*)" should not be blocked$/ do |enterprise| - Enterprise.find_by_name(enterprise).blocked?.should_not be_truthy + Enterprise.find_by(name: enterprise).blocked?.should_not be_truthy end Given /^enterprise template must be replaced after enable$/ do diff --git a/features/step_definitions/content_steps.rb b/features/step_definitions/content_steps.rb index 945770f..782145f 100644 --- a/features/step_definitions/content_steps.rb +++ b/features/step_definitions/content_steps.rb @@ -10,11 +10,11 @@ When /^I create a content of type "([^\"]*)" with the following data$/ do |conte end And /^I add to "([^\"]*)" the following exception "([^\"]*)"$/ do |article_name, user_exception| - article = Article.find_by_name(article_name) + article = Article.find_by(name: article_name) community = article.profile raise "The article profile is not a community." unless community.class == Community - my_user = community.members.find_by_name(user_exception) + my_user = community.members.find_by(name: user_exception) raise "Could not find #{user_exception} in #{community.name} community." if my_user.nil? article.article_privacy_exceptions << my_user diff --git a/features/step_definitions/create_community_steps.rb b/features/step_definitions/create_community_steps.rb index b5c723c..0797694 100644 --- a/features/step_definitions/create_community_steps.rb +++ b/features/step_definitions/create_community_steps.rb @@ -33,7 +33,7 @@ Given /^I reject community "(.+)"$/ do |community| end Then /^I should see "([^\"]*)"'s creation date$/ do |community| - com = Community.find_by_name community + com = Community.find_by name: community text = "Created at: #{show_date(com.created_at)}" has_content?(text) end diff --git a/features/step_definitions/invitation_steps.rb b/features/step_definitions/invitation_steps.rb index ace9029..6cf1554 100644 --- a/features/step_definitions/invitation_steps.rb +++ b/features/step_definitions/invitation_steps.rb @@ -1,5 +1,5 @@ Given /^I invite email "(.+)" to join community "(.+)"$/ do |email, community| - identifier = Community.find_by_name(community).identifier + identifier = Community.find_by(name: community).identifier visit("/myprofile/#{identifier}/profile_members") first(:link, "Invite people to join").click choose("Email") diff --git a/features/step_definitions/noosfero_steps.rb b/features/step_definitions/noosfero_steps.rb index 0526879..619f580 100644 --- a/features/step_definitions/noosfero_steps.rb +++ b/features/step_definitions/noosfero_steps.rb @@ -3,7 +3,7 @@ Given /^the following users?$/ do |table| table.hashes.each do |item| person_data = item.dup person_data.delete("login") - category = Category.find_by_slug person_data.delete("category") + category = Category.find_by slug: person_data.delete("category") email = item[:email] || item[:login] + "@example.com" user = User.create!(:login => item[:login], :password => '123456', :password_confirmation => '123456', :email => email, :person_data => person_data) user.activate @@ -15,12 +15,12 @@ Given /^the following users?$/ do |table| end Given /^"(.+)" is (invisible|visible)$/ do |user, visibility| - User.find_by_login(user).person.update({:visible => (visibility == 'visible')}, :without_protection => true) + User.find_by(login: user).person.update({visible: (visibility == 'visible')}, without_protection: true) end Given /^"(.+)" is (online|offline|busy) in chat$/ do |user, status| status = {'online' => 'chat', 'offline' => '', 'busy' => 'dnd'}[status] - User.find_by_login(user).update(:chat_status => status, :chat_status_at => DateTime.now) + User.find_by(login: user).update(:chat_status => status, :chat_status_at => DateTime.now) end Given /^the following (community|communities|enterprises?|organizations?)$/ do |kind,table| @@ -40,11 +40,11 @@ Given /^the following (community|communities|enterprises?|organizations?)$/ do | d.save(:validate => false) end if city - c = City.find_by_name city + c = City.find_by name: city organization.region = c end if category && !category.blank? - cat = Category.find_by_slug category + cat = Category.find_by slug: category ProfileCategorization.add_category_to_profile(cat, organization) end if img_name @@ -56,15 +56,15 @@ Given /^the following (community|communities|enterprises?|organizations?)$/ do | end Given /^"([^\"]*)" is associated with "([^\"]*)"$/ do |enterprise, bsc| - enterprise = Enterprise.find_by_name(enterprise) || Enterprise[enterprise] - bsc = BscPlugin::Bsc.find_by_name(bsc) || BscPlugin::Bsc[bsc] + enterprise = Enterprise.find_by(name: enterprise) || Enterprise[enterprise] + bsc = BscPlugin::Bsc.find_by(name: bsc) || BscPlugin::Bsc[bsc] bsc.enterprises << enterprise end Then /^"([^\"]*)" should be associated with "([^\"]*)"$/ do |enterprise, bsc| - enterprise = Enterprise.find_by_name(enterprise) || Enterprise[enterprise] - bsc = BscPlugin::Bsc.find_by_name(bsc) || BscPlugin::Bsc[bsc] + enterprise = Enterprise.find_by(name: enterprise) || Enterprise[enterprise] + bsc = BscPlugin::Bsc.find_by(name: bsc) || BscPlugin::Bsc[bsc] bsc.enterprises.should include(enterprise) end @@ -121,7 +121,7 @@ Given /^the following (articles|events|blogs|folders|forums|galleries|uploaded f translation_of_id = nil if item["translation_of"] if item["translation_of"] != "nil" - article = owner.articles.find_by_name(item["translation_of"]) + article = owner.articles.find_by(name: item["translation_of"]) translation_of_id = article.id if article end item.delete("translation_of") @@ -135,10 +135,10 @@ Given /^the following (articles|events|blogs|folders|forums|galleries|uploaded f end result = klass.new(item) if !parent.blank? - result.parent = Article.find_by_name(parent) + result.parent = Article.find_by(name: parent) end if category - cat = Category.find_by_slug category + cat = Category.find_by slug: category if cat result.add_category(cat) end @@ -157,7 +157,7 @@ Given /^the following files$/ do |table| file = "/files/#{item[:file]}" article = UploadedFile.new(:profile => owner, :uploaded_data => fixture_file_upload(file, item[:mime])) if item[:parent] - article.parent = Article.find_by_slug(item[:parent]) + article.parent = Article.find_by slug: item[:parent] end article.save! if item[:homepage] @@ -180,7 +180,7 @@ Given /^the following articles? with images?$/ do |table| img_tag += "/>" article = TinyMceArticle.new(:profile => owner, :name => item[:name], :body => img_tag) if item[:parent] - article.parent = Article.find_by_slug(item[:parent]) + article.parent = Article.find_by slug: item[:parent] end article.save! if item[:homepage] @@ -194,14 +194,14 @@ Given /^the following products?$/ do |table| table.hashes.each do |item| data = item.dup owner = Enterprise[data.delete("owner")] - category = Category.find_by_slug(data.delete("category").to_slug) + category = Category.find_by slug: data.delete("category").to_slug data.merge!(:enterprise => owner, :product_category => category) if data[:img] img = Image.create!(:uploaded_data => fixture_file_upload('/files/'+data.delete("img")+'.png', 'image/png')) data.merge!(:image_id => img.id) end if data[:qualifier] - qualifier = Qualifier.find_by_name(data.delete("qualifier")) + qualifier = Qualifier.find_by name: data.delete("qualifier") data.merge!(:qualifiers => [qualifier]) end product = Product.create!(data, :without_protection => true) @@ -211,9 +211,9 @@ end Given /^the following inputs?$/ do |table| table.hashes.each do |item| data = item.dup - product = Product.find_by_name(data.delete("product")) - category = Category.find_by_slug(data.delete("category").to_slug) - unit = Unit.find_by_singular(data.delete("unit")) + product = Product.find_by name: data.delete("product") + category = Category.find_by slug: data.delete("category").to_slug + unit = Unit.find_by singular: data.delete("unit") solidary = data.delete("solidary") input = Input.create!(data.merge(:product => product, :product_category => category, :unit => unit, :is_from_solidarity_economy => solidary), :without_protection => true) @@ -224,7 +224,7 @@ end Given /^the following states$/ do |table| table.hashes.each do |item| data = item.dup - if validator = Enterprise.find_by_name(data.delete("validator_name")) + if validator = Enterprise.find_by(name: data.delete("validator_name")) State.create!(data.merge(:environment => Environment.default, :validators => [validator]), :without_protection => true) else r = State.create!(data.merge(:environment => Environment.default)) @@ -235,7 +235,7 @@ end Given /^the following validation info$/ do |table| table.hashes.each do |item| data = item.dup - organization = Organization.find_by_name(data.delete("organization_name")) + organization = Organization.find_by name: data.delete("organization_name") ValidationInfo.create!(data.merge(:organization => organization)) end end @@ -245,7 +245,7 @@ Given /^the following (product_categories|product_category|category|categories|r table.hashes.each do |row| parent = row.delete("parent") if !parent.blank? - parent = Category.find_by_slug(parent.to_slug) + parent = Category.find_by slug: parent.to_slug row.merge!({:parent_id => parent.id}) end category = klass.create!({:environment => Environment.default}.merge(row)) @@ -263,7 +263,7 @@ Given /^the following certifiers$/ do |table| row = row.dup qualifiers_list = row.delete("qualifiers") if qualifiers_list - row["qualifiers"] = qualifiers_list.split(', ').map{|i| Qualifier.find_by_name(i)} + row["qualifiers"] = qualifiers_list.split(', ').map{|i| Qualifier.find_by name: i } end Certifier.create!(row.merge(:environment_id => 1), :without_protection => true) end @@ -279,8 +279,8 @@ end Given /^the following price details?$/ do |table| table.hashes.map{|item| item.dup}.each do |item| - product = Product.find_by_name item.delete('product') - production_cost = ProductionCost.find_by_name item.delete('production_cost') + product = Product.find_by name: item.delete('product') + production_cost = ProductionCost.find_by name: item.delete('production_cost') product.price_details.create!(item.merge(:production_cost => production_cost)) end end @@ -297,7 +297,7 @@ Given /^I am logged in as "(.+)"$/ do |username| end Given /^"([^"]*)" is environment admin$/ do |person| - user = Profile.find_by_name(person) + user = Profile.find_by name: person e = Environment.default e.add_admin(user) @@ -337,41 +337,41 @@ Given /^"(.+)" is a member of "(.+)"$/ do |person, profile| end Then /^"(.+)" should be a member of "(.+)"$/ do |person,profile| - Profile.find_by_name(profile).members.should include(Person.find_by_name(person)) + Profile.find_by(name: profile).members.should include(Person.find_by(name: person)) end When /^"(.*)" is accepted on community "(.*)"$/ do |person, community| - person = Person.find_by_name(person) - community = Community.find_by_name(community) + person = Person.find_by name: person + community = Community.find_by name: community community.affiliate(person, Profile::Roles.member(community.environment.id)) end Given /^"(.+)" is admin of "(.+)"$/ do |person, organization| - org = Profile.find_by_name(organization) - user = Profile.find_by_name(person) + org = Profile.find_by name: organization + user = Profile.find_by name: person org.add_admin(user) end Given /^"(.+)" is moderator of "(.+)"$/ do |person, organization| - org = Profile.find_by_name(organization) - user = Profile.find_by_name(person) + org = Profile.find_by name: organization + user = Profile.find_by name: person org.add_moderator(user) end Then /^"(.+)" should be admin of "(.+)"$/ do |person, organization| - org = Organization.find_by_name(organization) - user = Person.find_by_name(person) + org = Organization.find_by name: organization + user = Person.find_by name: person org.admins.should include(user) end Then /^"(.+)" should be moderator of "(.+)"$/ do |person,profile| - profile = Profile.find_by_name(profile) - person = Person.find_by_name(person) + profile = Profile.find_by name: profile + person = Person.find_by name: person profile.members_by_role(Profile::Roles.moderator(profile.environment.id)).should include(person) end Given /^"([^\"]*)" has no articles$/ do |profile| - (Profile[profile] || Profile.find_by_name(profile)).articles.delete_all + (Profile[profile] || Profile.find_by(name: profile)).articles.delete_all end Given /^the following (\w+) fields are (\w+) fields$/ do |klass, status, table| @@ -393,7 +393,7 @@ Given /^the following (\w+) fields are (\w+) fields$/ do |klass, status, table| end Then /^"([^\"]*)" should have the following data$/ do |id, table| - profile = Profile.find_by_identifier(id) + profile = Profile.find_by identifier: id expected = table.hashes.first data = expected.keys.inject({}) { |hash, key| hash[key] = profile.send(key).to_s; hash } data.should == expected @@ -408,12 +408,12 @@ Given /^"(.+)" is friend of "(.+)"$/ do |person, friend| end Given /^enterprise "([^\"]*)" is blocked$/ do |enterprise_name| - enterprise = Enterprise.find_by_name(enterprise_name) + enterprise = Enterprise.find_by name: enterprise_name enterprise.block end Given /^enterprise "([^\"]*)" is disabled$/ do |enterprise_name| - enterprise = Enterprise.find_by_name(enterprise_name) + enterprise = Enterprise.find_by name: enterprise_name enterprise.enabled = false enterprise.save end @@ -470,7 +470,7 @@ Given /^the profile "(.+)" has no blocks$/ do |profile| end Given /^the articles of "(.+)" are moderated$/ do |organization| - organization = Organization.find_by_name(organization) + organization = Organization.find_by name: organization organization.moderated_articles = true organization.save end @@ -478,7 +478,7 @@ end Given /^the following comments?$/ do |table| table.hashes.each do |item| data = item.dup - article = Article.find_by_name(data.delete("article")) + article = Article.find_by name: data.delete("article") author = data.delete("author") comment = article.comments.build(data) if author @@ -489,7 +489,7 @@ Given /^the following comments?$/ do |table| end Given /^the community "(.+)" is closed$/ do |community| - community = Community.find_by_name(community) + community = Community.find_by name: community community.closed = true community.save end @@ -510,8 +510,8 @@ Given /^the following units?$/ do |table| end Given /^"([^\"]*)" asked to join "([^\"]*)"$/ do |person, organization| - person = Person.find_by_name(person) - organization = Organization.find_by_name(organization) + person = Person.find_by name: person + organization = Organization.find_by name: organization AddMember.create!(:person => person, :organization => organization) end @@ -531,7 +531,7 @@ Given /^the environment domain is "([^\"]*)"$/ do |domain| end When /^([^\']*)'s account is activated$/ do |person| - Person.find_by_name(person).user.activate + Person.find_by(name: person).user.activate end Then /^I should receive an e-mail on (.*)$/ do |address| @@ -547,13 +547,13 @@ end Then /^there should be an? (.+) named "([^\"]*)"$/ do |klass_name, profile_name| klass = klass_name.camelize.constantize - klass.find_by_name(profile_name).nil?.should be_falsey + klass.find_by(name: profile_name).nil?.should be_falsey end Then /^"([^\"]*)" profile should exist$/ do |profile_selector| profile = nil begin - profile = Profile.find_by_name(profile_selector) + profile = Profile.find_by(name: profile_selector) profile.nil?.should be_falsey rescue profile.nil?.should be_falsey @@ -563,7 +563,7 @@ end Then /^"([^\"]*)" profile should not exist$/ do |profile_selector| profile = nil begin - profile = Profile.find_by_name(profile_selector) + profile = Profile.find_by(name: profile_selector) profile.nil?.should be_truthy rescue profile.nil?.should be_truthy @@ -575,7 +575,7 @@ When 'I log off' do end Then /^I should be taken to "([^\"]*)" product page$/ do |product_name| - product = Product.find_by_name(product_name) + product = Product.find_by(name: product_name) path = url_for(product.enterprise.public_profile_url.merge(:controller => 'manage_products', :action => 'show', :id => product, :only_path => true)) if response.class.to_s == 'Webrat::SeleniumResponse' URI.parse(response.selenium.get_location).path.should == path_to(path) @@ -589,7 +589,7 @@ Given /^the following enterprise homepages?$/ do |table| table.hashes.each do |item| data = item.dup home = EnterpriseHomepage.new(:name => data[:name]) - ent = Enterprise.find_by_identifier(data[:enterprise]) + ent = Enterprise.find_by(identifier: data[:enterprise]) ent.articles << home end end @@ -609,7 +609,7 @@ end Given /^the following cities$/ do |table| table.hashes.each do |item| - state = State.find_by_acronym item[:state] + state = State.find_by acronym: item[:state] if !state state = State.create!(:name => item[:state], :acronym => item[:state], :environment_id => Environment.default.id) end @@ -626,7 +626,7 @@ end Given /^the following tags$/ do |table| table.hashes.each do |item| - article = Article.find_by_name item[:article] + article = Article.find_by name: item[:article] article.tag_list.add item[:name] article.save! end @@ -639,7 +639,7 @@ When /^I search ([^\"]*) for "([^\"]*)"$/ do |asset, query| end Then /^I should see ([^\"]*)'s product image$/ do |product_name| - p = Product.find_by_name product_name + p = Product.find_by name: product_name path = url_for(p.enterprise.public_profile_url.merge(:controller => 'manage_products', :action => 'show', :id => p)) with_scope('.zoomable-image') do @@ -648,7 +648,7 @@ Then /^I should see ([^\"]*)'s product image$/ do |product_name| end Then /^I should not see ([^\"]*)'s product image$/ do |product_name| - p = Product.find_by_name product_name + p = Product.find_by name: product_name path = url_for(p.enterprise.public_profile_url.merge(:controller => 'manage_products', :action => 'show', :id => p)) with_scope('.zoomable-image') do @@ -673,14 +673,14 @@ Then /^I should not see ([^\"]*)'s community image$/ do |name| end Given /^the article "([^\"]*)" is updated by "([^\"]*)"$/ do |article, person| - a = Article.find_by_name article - p = Person.find_by_name person + a = Article.find_by name: article + p = Person.find_by name: person a.last_changed_by = p a.save! end Given /^the article "([^\"]*)" is updated with$/ do |article, table| - a = Article.find_by_name article + a = Article.find_by name: article row = table.hashes.first a.update(row) end @@ -720,7 +720,7 @@ Given /^the profile (.*) is configured to (.*) after login$/ do |profile, option when 'redirect to profile control panel' 'user_control_panel' end - profile = Profile.find_by_identifier(profile) + profile = Profile.find_by identifier: profile profile.redirection_after_login = redirection profile.save end diff --git a/features/support/paths.rb b/features/support/paths.rb index 7ce77ac..90fee6a 100644 --- a/features/support/paths.rb +++ b/features/support/paths.rb @@ -15,7 +15,7 @@ module NavigationHelpers # Here is an example that pulls values out of the Regexp: # # when /^(.*)'s profile page$/i - # user_profile_path(User.find_by_login($1)) + # user_profile_path(User.find_by(login: $1)) when /^\// page_name @@ -24,19 +24,19 @@ module NavigationHelpers '/site/welcome' when /article "([^"]+)"\s*$/ - url_for(Article.find_by_name($1).url.merge({:only_path => true})) + url_for(Article.find_by(name: $1).url.merge({:only_path => true})) when /category "([^"]+)"/ - '/cat/%s' % Category.find_by_name($1).slug + '/cat/%s' % Category.find_by(name: $1).slug when /edit "(.+)" by (.+)/ - article_id = Person[$2].articles.find_by_slug($1.to_slug).id + article_id = Person[$2].articles.find_by(slug: $1.to_slug).id "/myprofile/#{$2}/cms/edit/#{article_id}" when /edit (.*Block) of (.+)/ owner = Profile[$2] klass = $1.constantize - block = klass.find(:all).select{|i| i.owner == owner}.first + block = klass.all.select{|i| i.owner == owner}.first "/myprofile/#{$2}/profile_design/edit/#{block.id}" when /^(.*)'s homepage$/ @@ -85,18 +85,18 @@ module NavigationHelpers '/myprofile/%s/cms' % profile_identifier($1) when /^"(.+)" edit page/ - article = Article.find_by_name($1) + article = Article.find_by name: $1 '/myprofile/%s/cms/edit/%s' % [article.profile.identifier, article.id] when /^(.+)'s members management/ - '/myprofile/%s/profile_members' % Profile.find_by_name($1).identifier + '/myprofile/%s/profile_members' % Profile.find_by(name: $1).identifier when /^(.+)'s new product page/ '/myprofile/%s/manage_products/new' % profile_identifier($1) when /^(.+)'s page of product (.*)$/ - enterprise = Profile.find_by_name($1) - product = enterprise.products.find_by_name($2) + enterprise = Profile.find_by(name: $1) + product = enterprise.products.find_by(name: $2) '/myprofile/%s/manage_products/show/%s' % [enterprise.identifier, product.id] when /^(.*)'s products page$/ @@ -138,7 +138,7 @@ module NavigationHelpers end def profile_identifier(field) - profile = Profile.find_by_name(field) || Profile.find_by_identifier(field) + profile = Profile.find_by(name: field) || Profile.find_by(identifier: field) profile.identifier end end diff --git a/lib/acts_as_filesystem.rb b/lib/acts_as_filesystem.rb index 0e729ad..919bf91 100644 --- a/lib/acts_as_filesystem.rb +++ b/lib/acts_as_filesystem.rb @@ -120,7 +120,7 @@ module ActsAsFileSystem def top_ancestor if has_ancestry? and !ancestry.nil? - self.class.base_class.find_by_id self.top_ancestor_id + self.class.base_class.find_by id: self.top_ancestor_id else self.hierarchy.first end diff --git a/lib/acts_as_having_boxes.rb b/lib/acts_as_having_boxes.rb index 77a82cd..c6d1383 100644 --- a/lib/acts_as_having_boxes.rb +++ b/lib/acts_as_having_boxes.rb @@ -2,7 +2,7 @@ module ActsAsHavingBoxes module ClassMethods def acts_as_having_boxes - has_many :boxes, :as => :owner, :dependent => :destroy, :order => 'position' + has_many :boxes, -> { order :position }, as: :owner, dependent: :destroy self.send(:include, ActsAsHavingBoxes) end end diff --git a/lib/acts_as_having_posts.rb b/lib/acts_as_having_posts.rb index 701823a..c8c3fc3 100644 --- a/lib/acts_as_having_posts.rb +++ b/lib/acts_as_having_posts.rb @@ -1,8 +1,12 @@ module ActsAsHavingPosts module ClassMethods - def acts_as_having_posts(options = {}) - has_many :posts, { :class_name => 'Article', :foreign_key => 'parent_id', :source => :children, :conditions => [ 'articles.type != ?', 'RssFeed' ], :order => 'published_at DESC, id DESC' }.merge(options) + def acts_as_having_posts(scope = nil) + has_many :posts, -> { + s = order('published_at DESC, id DESC').where('articles.type != ?', 'RssFeed') + s = s.instance_exec(&scope) if scope + s + }, class_name: 'Article', foreign_key: 'parent_id', source: :children attr_accessor :feed_attrs diff --git a/lib/noosfero/action_tracker_ext.rb b/lib/noosfero/action_tracker_ext.rb index a3463be..c684c02 100644 --- a/lib/noosfero/action_tracker_ext.rb +++ b/lib/noosfero/action_tracker_ext.rb @@ -9,7 +9,9 @@ Rails.configuration.to_prepare do end end - has_many :profile_activities, foreign_key: :activity_id, conditions: {profile_activities: {activity_type: 'ActionTracker::Record'}}, dependent: :destroy + has_many :profile_activities, -> { + where profile_activities: {activity_type: 'ActionTracker::Record'} + }, foreign_key: :activity_id, dependent: :destroy after_create :create_activity after_update :update_activity diff --git a/lib/noosfero/api/helpers.rb b/lib/noosfero/api/helpers.rb index 952a84d..dcdae61 100644 --- a/lib/noosfero/api/helpers.rb +++ b/lib/noosfero/api/helpers.rb @@ -22,7 +22,7 @@ require_relative '../../find_by_contents' def current_user private_token = (params[PRIVATE_TOKEN_PARAM] || headers['Private-Token']).to_s - @current_user ||= User.find_by_private_token(private_token) + @current_user ||= User.find_by private_token: private_token @current_user end @@ -268,7 +268,7 @@ require_relative '../../find_by_contents' # keys (unique) - A hash consisting of keys that must be unique def unique_attributes!(obj, keys) keys.each do |key| - cant_be_saved_request!(key) if obj.send("find_by_#{key.to_s}", params[key]) + cant_be_saved_request!(key) if obj.find_by(key.to_s => params[key]) end end @@ -342,7 +342,7 @@ require_relative '../../find_by_contents' end def detect_stuff_by_domain - @domain = Domain.find_by_name(request.host) + @domain = Domain.by_name(request.host) if @domain.nil? @environment = Environment.default if @environment.nil? && Rails.env.development? diff --git a/lib/noosfero/api/session.rb b/lib/noosfero/api/session.rb index 2eb6ed6..90c66d1 100644 --- a/lib/noosfero/api/session.rb +++ b/lib/noosfero/api/session.rb @@ -73,7 +73,7 @@ module Noosfero # Example Request: # PATCH /activate?activation_code=28259abd12cc6a64ef9399cf3286cb998b96aeaf patch "/activate" do - user = User.find_by_activation_code(params[:activation_code]) + user = User.find_by activation_code: params[:activation_code] if user unless user.environment.enabled?('admin_must_approve_new_users') if user.activate @@ -141,7 +141,7 @@ module Noosfero # Example Request: # PATCH /new_password?code=xxxx&password=secret&password_confirmation=secret patch "/new_password" do - change_password = ChangePassword.find_by_code(params[:code]) + change_password = ChangePassword.find_by code: params[:code] not_found! if change_password.nil? if change_password.update_attributes(:password => params[:password], :password_confirmation => params[:password_confirmation]) diff --git a/lib/noosfero/api/v1/activities.rb b/lib/noosfero/api/v1/activities.rb index 092318b..5b64e00 100644 --- a/lib/noosfero/api/v1/activities.rb +++ b/lib/noosfero/api/v1/activities.rb @@ -9,7 +9,7 @@ module Noosfero get ':id/activities' do profile = environment.profiles profile = profile.visible_for_person(current_person) if profile.respond_to?(:visible_for_person) - profile = profile.find_by_id(params[:id]) + profile = profile.find_by id: params[:id] activities = profile.activities.map(&:activity) present activities, :with => Entities::Activity, :current_person => current_person end diff --git a/lib/noosfero/api/v1/articles.rb b/lib/noosfero/api/v1/articles.rb index 3b243e3..309059d 100644 --- a/lib/noosfero/api/v1/articles.rb +++ b/lib/noosfero/api/v1/articles.rb @@ -74,7 +74,7 @@ module Noosfero current_person.register_report(abuse_report, profile) if !params[:content_type].blank? - abuse_report = AbuseReport.find_by_reporter_id_and_abuse_complaint_id(current_person.id, profile.opened_abuse_complaint.id) + abuse_report = AbuseReport.find_by reporter_id: current_person.id, abuse_complaint_id: profile.opened_abuse_complaint.id Delayed::Job.enqueue DownloadReportedImagesJob.new(abuse_report, article) end @@ -253,7 +253,7 @@ module Noosfero get ':id/home_page' do profiles = environment.profiles profiles = profiles.visible_for_person(current_person) - profile = profiles.find_by_id(params[:id]) + profile = profiles.find_by id: params[:id] present_partial profile.home_page, :with => Entities::Article end end @@ -275,7 +275,7 @@ module Noosfero profile = environment.send(kind.pluralize).find(params["#{kind}_id"]) if params[:path].present? - article = profile.articles.find_by_path(params[:path]) + article = profile.articles.find_by path: params[:path] if !article || !article.display_to?(current_person) article = forbidden! end diff --git a/lib/noosfero/api/v1/communities.rb b/lib/noosfero/api/v1/communities.rb index ead1e51..68ad55c 100644 --- a/lib/noosfero/api/v1/communities.rb +++ b/lib/noosfero/api/v1/communities.rb @@ -49,7 +49,7 @@ module Noosfero end get ':id' do - community = environment.communities.visible_for_person(current_person).find_by_id(params[:id]) + community = environment.communities.visible_for_person(current_person).find_by id: params[:id] present community, :with => Entities::Community, :current_person => current_person end diff --git a/lib/noosfero/api/v1/enterprises.rb b/lib/noosfero/api/v1/enterprises.rb index fea8475..345ca82 100644 --- a/lib/noosfero/api/v1/enterprises.rb +++ b/lib/noosfero/api/v1/enterprises.rb @@ -26,7 +26,7 @@ module Noosfero desc "Return one enterprise by id" get ':id' do - enterprise = environment.enterprises.visible_for_person(current_person).find_by_id(params[:id]) + enterprise = environment.enterprises.visible_for_person(current_person).find_by id: params[:id] present enterprise, :with => Entities::Enterprise, :current_person => current_person end diff --git a/lib/noosfero/api/v1/people.rb b/lib/noosfero/api/v1/people.rb index 8179c66..8b4950f 100644 --- a/lib/noosfero/api/v1/people.rb +++ b/lib/noosfero/api/v1/people.rb @@ -46,7 +46,7 @@ module Noosfero desc "Return the person information" get ':id' do - person = environment.people.visible_for_person(current_person).find_by_id(params[:id]) + person = environment.people.visible_for_person(current_person).find_by id: params[:id] return not_found! if person.blank? present person, :with => Entities::Person, :current_person => current_person end @@ -87,7 +87,7 @@ module Noosfero desc "Return the person friends" get ':id/friends' do - person = environment.people.visible_for_person(current_person).find_by_id(params[:id]) + person = environment.people.visible_for_person(current_person).find_by id: params[:id] return not_found! if person.blank? friends = person.friends.visible present friends, :with => Entities::Person, :current_person => current_person @@ -114,7 +114,7 @@ module Noosfero resource :members do paginate max_per_page: MAX_PER_PAGE get do - profile = environment.profiles.find_by_id(params[:profile_id]) + profile = environment.profiles.find_by id: params[:profile_id] members = select_filtered_collection_of(profile, 'members', params) present members, :with => Entities::Person, :current_person => current_person end diff --git a/lib/noosfero/api/v1/profiles.rb b/lib/noosfero/api/v1/profiles.rb index 302fd7a..84c82bb 100644 --- a/lib/noosfero/api/v1/profiles.rb +++ b/lib/noosfero/api/v1/profiles.rb @@ -16,7 +16,7 @@ module Noosfero get ':id' do profiles = environment.profiles profiles = profiles.visible_for_person(current_person) - profile = profiles.find_by_id(params[:id]) + profile = profiles.find_by id: params[:id] present profile, :with => Entities::Profile, :current_person => current_person end end diff --git a/lib/noosfero/api/v1/users.rb b/lib/noosfero/api/v1/users.rb index c62adde..f494d5d 100644 --- a/lib/noosfero/api/v1/users.rb +++ b/lib/noosfero/api/v1/users.rb @@ -17,7 +17,7 @@ module Noosfero end get ":id" do - user = environment.users.find_by_id(params[:id]) + user = environment.users.find_by id: params[:id] unless user.person.display_info_to? current_person unauthorized! end diff --git a/lib/noosfero/core_ext/active_record.rb b/lib/noosfero/core_ext/active_record.rb index ed5d9f8..4370861 100644 --- a/lib/noosfero/core_ext/active_record.rb +++ b/lib/noosfero/core_ext/active_record.rb @@ -63,8 +63,12 @@ class ActiveRecord::Base end ActiveRecord::Calculations.class_eval do - def count_with_distinct column_name=nil, options={} - distinct.count_without_distinct column_name, options + def count_with_distinct column_name=self.primary_key + if column_name + distinct.count_without_distinct column_name + else + count_without_distinct + end end alias_method_chain :count, :distinct end diff --git a/lib/time_scopes.rb b/lib/time_scopes.rb index 6642c7e..a3b5635 100644 --- a/lib/time_scopes.rb +++ b/lib/time_scopes.rb @@ -8,11 +8,11 @@ module TimeScopes if base.respond_to?(:scope) && base.attribute_names.include?('created_at') base.class_eval do scope :younger_than, lambda { |created_at| - {:conditions => ["#{table_name}.created_at > ?", created_at]} + where "#{table_name}.created_at > ?", created_at } scope :older_than, lambda { |created_at| - {:conditions => ["#{table_name}.created_at < ?", created_at]} + where "#{table_name}.created_at < ?", created_at } end end diff --git a/plugins/analytics/test/functional/content_viewer_controller_test.rb b/plugins/analytics/test/functional/content_viewer_controller_test.rb index 1fafb53..a64bf45 100644 --- a/plugins/analytics/test/functional/content_viewer_controller_test.rb +++ b/plugins/analytics/test/functional/content_viewer_controller_test.rb @@ -37,7 +37,7 @@ class ContentViewerControllerTest < ActionController::TestCase @request.env['HTTP_REFERER'] = first_url get :view_page, profile: @community.identifier, page: @community.articles.last.path.split('/') assert_equal 2, @community.page_views.count - assert_equal 1, @community.visits.count + assert_equal 2, @community.visits.count second_page_view = @community.page_views.order(:id).last assert_equal first_page_view, second_page_view.referer_page_view @@ -48,7 +48,7 @@ class ContentViewerControllerTest < ActionController::TestCase future = Time.now + 2*AnalyticsPlugin::TimeOnPageUpdateInterval Time.stubs(:now).returns(future) get :view_page, profile: @community.identifier, page: @community.articles.last.path.split('/') - assert_equal 2, @community.visits.count + assert_equal 3, @community.visits.count end end diff --git a/plugins/comment_classification/lib/comment_classification_plugin.rb b/plugins/comment_classification/lib/comment_classification_plugin.rb index 69c35eb..d2f0537 100644 --- a/plugins/comment_classification/lib/comment_classification_plugin.rb +++ b/plugins/comment_classification/lib/comment_classification_plugin.rb @@ -36,8 +36,8 @@ class CommentClassificationPlugin < Noosfero::Plugin comment = Comment.find args[0] label_id = args[1][:comment_label_id] if label_id.blank? - if !CommentClassificationPlugin::CommentLabelUser.find_by_comment_id(comment.id).nil? - CommentClassificationPlugin::CommentLabelUser.find_by_comment_id(comment.id).destroy + if !CommentClassificationPlugin::CommentLabelUser.find_by(comment_id: comment.id).nil? + CommentClassificationPlugin::CommentLabelUser.find_by(comment_id: comment.id).destroy end else label = CommentClassificationPlugin::Label.find label_id diff --git a/plugins/comment_paragraph/lib/ext/article.rb b/plugins/comment_paragraph/lib/ext/article.rb index a00565e..5305ad7 100644 --- a/plugins/comment_paragraph/lib/ext/article.rb +++ b/plugins/comment_paragraph/lib/ext/article.rb @@ -2,7 +2,10 @@ require_dependency 'article' class Article - has_many :paragraph_comments, :class_name => 'Comment', :foreign_key => 'source_id', :dependent => :destroy, :order => 'created_at asc', :conditions => [ 'paragraph_uuid IS NOT NULL'] + has_many :paragraph_comments, -> { + order('created_at ASC') + .where('paragraph_uuid IS NOT NULL') + }, class_name: 'Comment', foreign_key: 'source_id', dependent: :destroy before_save :comment_paragraph_plugin_parse_html diff --git a/plugins/comment_paragraph/lib/ext/comment.rb b/plugins/comment_paragraph/lib/ext/comment.rb index edc26de..16f4abf 100644 --- a/plugins/comment_paragraph/lib/ext/comment.rb +++ b/plugins/comment_paragraph/lib/ext/comment.rb @@ -2,14 +2,13 @@ require_dependency 'comment' class Comment - scope :without_paragraph, :conditions => {:paragraph_uuid => nil } + scope :without_paragraph, -> { where paragraph_uuid: nil } settings_items :comment_paragraph_selected_area, :type => :string settings_items :comment_paragraph_selected_content, :type => :string - scope :in_paragraph, proc { |paragraph_uuid| { - :conditions => ['paragraph_uuid = ?', paragraph_uuid] - } + scope :in_paragraph, -> paragraph_uuid { + where 'paragraph_uuid = ?', paragraph_uuid } attr_accessible :paragraph_uuid, :comment_paragraph_selected_area, :id, :comment_paragraph_selected_content diff --git a/plugins/community_track/lib/community_track_plugin/step.rb b/plugins/community_track/lib/community_track_plugin/step.rb index e83ac50..3848a4b 100644 --- a/plugins/community_track/lib/community_track_plugin/step.rb +++ b/plugins/community_track/lib/community_track_plugin/step.rb @@ -7,7 +7,7 @@ class CommunityTrackPlugin::Step < Folder alias :tools :children - acts_as_list :scope => :parent + acts_as_list scope: -> step { where parent_id: step.parent_id } def belong_to_track errors.add(:parent, _("Step not allowed at this parent.")) unless parent.kind_of?(CommunityTrackPlugin::Track) diff --git a/plugins/community_track/test/functional/community_track_plugin_public_controller_test.rb b/plugins/community_track/test/functional/community_track_plugin_public_controller_test.rb index b84c42b..f1940a1 100644 --- a/plugins/community_track/test/functional/community_track_plugin_public_controller_test.rb +++ b/plugins/community_track/test/functional/community_track_plugin_public_controller_test.rb @@ -105,10 +105,10 @@ class CommunityTrackPluginPublicControllerTest < ActionController::TestCase per_page = 4 (per_page*3).times {|i| create_track("track_#{i}", @community) } - tracks = 3.times.map do |i| + tracks = 3.times.flat_map do |i| xhr :get, :view_tracks, :id => @block.id, :page => i+1, :per_page => per_page assigns[:tracks].all - end.flatten + end assert_equal tracks.count, tracks.uniq.count end diff --git a/plugins/custom_forms/controllers/custom_forms_plugin_profile_controller.rb b/plugins/custom_forms/controllers/custom_forms_plugin_profile_controller.rb index e5155cb..0f3ba5c 100644 --- a/plugins/custom_forms/controllers/custom_forms_plugin_profile_controller.rb +++ b/plugins/custom_forms/controllers/custom_forms_plugin_profile_controller.rb @@ -6,7 +6,7 @@ class CustomFormsPluginProfileController < ProfileController @form = CustomFormsPlugin::Form.find(params[:id]) if user - @submission = CustomFormsPlugin::Submission.find_by_form_id_and_profile_id(@form.id,user.id) + @submission = CustomFormsPlugin::Submission.find_by form_id: @form.id, profile_id: user.id @submission ||= CustomFormsPlugin::Submission.new(:form => @form, :profile => user) else @submission = CustomFormsPlugin::Submission.new(:form => @form) @@ -17,7 +17,7 @@ class CustomFormsPluginProfileController < ProfileController if request.post? begin - raise 'Submission already present!' if user.present? && CustomFormsPlugin::Submission.find_by_form_id_and_profile_id(@form.id,user.id) + raise 'Submission already present!' if user.present? && CustomFormsPlugin::Submission.find_by(form_id: @form.id, profile_id: user.id) raise 'Form expired!' if @form.expired? if !user diff --git a/plugins/custom_forms/lib/custom_forms_plugin/field.rb b/plugins/custom_forms/lib/custom_forms_plugin/field.rb index ae3d2d0..76c9401 100644 --- a/plugins/custom_forms/lib/custom_forms_plugin/field.rb +++ b/plugins/custom_forms/lib/custom_forms_plugin/field.rb @@ -9,7 +9,7 @@ class CustomFormsPlugin::Field < ActiveRecord::Base belongs_to :form, :class_name => 'CustomFormsPlugin::Form' has_many :answers, :class_name => 'CustomFormsPlugin::Answer', :dependent => :destroy - has_many :alternatives, :order => 'position', :class_name => 'CustomFormsPlugin::Alternative' + has_many :alternatives, -> { order 'position' }, class_name: 'CustomFormsPlugin::Alternative' accepts_nested_attributes_for :alternatives, :allow_destroy => true #FIXME This validation should be in the subclass, but since we are using Single Table # Inheritance we are instantiating a Field object with the type as a param. So the validation diff --git a/plugins/custom_forms/lib/custom_forms_plugin/form.rb b/plugins/custom_forms/lib/custom_forms_plugin/form.rb index 1d8fb02..1678fa7 100644 --- a/plugins/custom_forms/lib/custom_forms_plugin/form.rb +++ b/plugins/custom_forms/lib/custom_forms_plugin/form.rb @@ -2,7 +2,7 @@ class CustomFormsPlugin::Form < ActiveRecord::Base belongs_to :profile - has_many :fields, :order => 'position', :class_name => 'CustomFormsPlugin::Field', :dependent => :destroy + has_many :fields, -> { order 'position' }, class_name: 'CustomFormsPlugin::Field', dependent: :destroy accepts_nested_attributes_for :fields, :allow_destroy => true has_many :submissions, :class_name => 'CustomFormsPlugin::Submission', :dependent => :destroy diff --git a/plugins/custom_forms/lib/custom_forms_plugin/submission.rb b/plugins/custom_forms/lib/custom_forms_plugin/submission.rb index 8f60f5f..8cfb5d3 100644 --- a/plugins/custom_forms/lib/custom_forms_plugin/submission.rb +++ b/plugins/custom_forms/lib/custom_forms_plugin/submission.rb @@ -15,7 +15,7 @@ class CustomFormsPlugin::Submission < ActiveRecord::Base validate :check_answers def self.human_attribute_name_with_customization(attrib, options={}) - if /\d+/ =~ attrib and (f = CustomFormsPlugin::Field.find_by_id(attrib.to_s)) + if /\d+/ =~ attrib and (f = CustomFormsPlugin::Field.find_by(id: attrib.to_s)) f.name else _(self.human_attribute_name_without_customization(attrib)) diff --git a/plugins/custom_forms/test/functional/custom_forms_plugin_myprofile_controller_test.rb b/plugins/custom_forms/test/functional/custom_forms_plugin_myprofile_controller_test.rb index 0dd8070..f3737df 100644 --- a/plugins/custom_forms/test/functional/custom_forms_plugin_myprofile_controller_test.rb +++ b/plugins/custom_forms/test/functional/custom_forms_plugin_myprofile_controller_test.rb @@ -66,7 +66,7 @@ class CustomFormsPluginMyprofileControllerTest < ActionController::TestCase } end - form = CustomFormsPlugin::Form.find_by_name('My Form') + form = CustomFormsPlugin::Form.find_by(name: 'My Form') assert_equal 'logged', form.access assert_equal begining, form.begining.strftime(format) assert_equal ending, form.ending.strftime(format) @@ -110,7 +110,7 @@ class CustomFormsPluginMyprofileControllerTest < ActionController::TestCase :fields_attributes => fields } end - form = CustomFormsPlugin::Form.find_by_name('My Form') + form = CustomFormsPlugin::Form.find_by(name: 'My Form') assert_equal num_fields, form.fields.count lst = 10 form.fields.each do |f| @@ -147,7 +147,7 @@ class CustomFormsPluginMyprofileControllerTest < ActionController::TestCase :fields_attributes => fields } end - form = CustomFormsPlugin::Form.find_by_name('My Form') + form = CustomFormsPlugin::Form.find_by(name: 'My Form') assert_equal 2, form.fields.count assert form.fields.first.name == "1" assert form.fields.last.name == "0" diff --git a/plugins/delivery/controllers/myprofile/delivery_plugin/admin_method_controller.rb b/plugins/delivery/controllers/myprofile/delivery_plugin/admin_method_controller.rb index 0262f43..f640cb4 100644 --- a/plugins/delivery/controllers/myprofile/delivery_plugin/admin_method_controller.rb +++ b/plugins/delivery/controllers/myprofile/delivery_plugin/admin_method_controller.rb @@ -13,7 +13,7 @@ class DeliveryPlugin::AdminMethodController < MyProfileController end def edit - @delivery_method ||= profile.delivery_methods.find_by_id params[:id] + @delivery_method ||= profile.delivery_methods.find_by id: params[:id] if params[:delivery_method].present? and @delivery_method.update params[:delivery_method] render partial: 'list' else diff --git a/plugins/environment_notification/controllers/environment_notification_plugin_admin_controller.rb b/plugins/environment_notification/controllers/environment_notification_plugin_admin_controller.rb index 4e2308f..11645bc 100644 --- a/plugins/environment_notification/controllers/environment_notification_plugin_admin_controller.rb +++ b/plugins/environment_notification/controllers/environment_notification_plugin_admin_controller.rb @@ -26,7 +26,7 @@ class EnvironmentNotificationPluginAdminController < AdminController def destroy if request.delete? - notification = environment.environment_notifications.find_by_id(params[:id]) + notification = environment.environment_notifications.find_by id: params[:id] if notification && notification.destroy session[:notice] = _('The notification was deleted.') else @@ -37,7 +37,7 @@ class EnvironmentNotificationPluginAdminController < AdminController end def edit - @notification = environment.environment_notifications.find_by_id(params[:id]) + @notification = environment.environment_notifications.find_by id: params[:id] if request.post? if @notification.update_attributes(params[:notifications]) session[:notice] = _('The notification was edited.') @@ -49,7 +49,7 @@ class EnvironmentNotificationPluginAdminController < AdminController end def change_status - @notification = environment.environment_notifications.find_by_id(params[:id]) + @notification = environment.environment_notifications.find_by id: params[:id] @notification.active = !@notification.active @@ -66,7 +66,7 @@ class EnvironmentNotificationPluginAdminController < AdminController result = false if logged_in? - @notification = environment.environment_notifications.find_by_id(params[:notification_id]) + @notification = environment.environment_notifications.find_by id: params[:notification_id] if @notification @notification.users << current_user @@ -81,7 +81,7 @@ class EnvironmentNotificationPluginAdminController < AdminController result = false if logged_in? - @notification = environment.environment_notifications.find_by_id(params[:notification_id]) + @notification = environment.environment_notifications.find_by id: params[:notification_id] if @notification current_notificaions = [] diff --git a/plugins/environment_notification/models/environment_notification_plugin/environment_notification.rb b/plugins/environment_notification/models/environment_notification_plugin/environment_notification.rb index ad91678..ba39ab0 100644 --- a/plugins/environment_notification/models/environment_notification_plugin/environment_notification.rb +++ b/plugins/environment_notification/models/environment_notification_plugin/environment_notification.rb @@ -24,7 +24,7 @@ class EnvironmentNotificationPlugin::EnvironmentNotification < ActiveRecord::Bas end end - scope :active, lambda{|environment| { :conditions => { :environment_id => environment.id, :active => true } } } + scope :active, -> environment { where environment_id: environment.id, active: true } def self.visibles(environment, user, controller_path) notifications = EnvironmentNotificationPlugin::EnvironmentNotification.active(environment).order('updated_at DESC') diff --git a/plugins/environment_notification/test/functional/environment_notification_plugin_admin_controller_test.rb b/plugins/environment_notification/test/functional/environment_notification_plugin_admin_controller_test.rb index 1ff4671..a0b784a 100644 --- a/plugins/environment_notification/test/functional/environment_notification_plugin_admin_controller_test.rb +++ b/plugins/environment_notification/test/functional/environment_notification_plugin_admin_controller_test.rb @@ -1,8 +1,5 @@ -require File.expand_path(File.dirname(__FILE__)) + '/../../../../test/test_helper' -require( - File.expand_path(File.dirname(__FILE__)) + - '/../../controllers/environment_notification_plugin_admin_controller' -) +require 'test_helper' +require_relative '../../controllers/environment_notification_plugin_admin_controller' class EnvironmentNotificationPluginAdminController; def rescue_action(e) raise e end; end @@ -94,7 +91,7 @@ class EnvironmentNotificationPluginAdminControllerTest < ActionController::TestC :type => "EnvironmentNotificationPlugin::DangerNotification" ) delete :destroy, :id => @notification.id - assert_nil EnvironmentNotificationPlugin::EnvironmentNotification.find_by_id(@notification.id) + assert_nil EnvironmentNotificationPlugin::EnvironmentNotification.find_by(id: @notification.id) end should 'an user not to be able to destroy a notification' do @@ -107,7 +104,7 @@ class EnvironmentNotificationPluginAdminControllerTest < ActionController::TestC delete :destroy, :id => @notification.id assert_redirected_to :root - assert_not_nil EnvironmentNotificationPlugin::EnvironmentNotification.find_by_id(@notification.id) + assert_not_nil EnvironmentNotificationPlugin::EnvironmentNotification.find_by(id: @notification.id) end should 'an admin be able to change Notification status' do diff --git a/plugins/gallery_block/lib/gallery_block.rb b/plugins/gallery_block/lib/gallery_block.rb index e577018..3614919 100644 --- a/plugins/gallery_block/lib/gallery_block.rb +++ b/plugins/gallery_block/lib/gallery_block.rb @@ -18,12 +18,12 @@ class GalleryBlock < Block def gallery if self.owner.kind_of? Environment - article = owner.articles.find_by_id(self.gallery_id) + article = owner.articles.find_by id: self.gallery_id if article && article.gallery? article end else - owner.image_galleries.find_by_id(self.gallery_id) + owner.image_galleries.find_by id: self.gallery_id end end diff --git a/plugins/newsletter/controllers/newsletter_plugin_admin_controller.rb b/plugins/newsletter/controllers/newsletter_plugin_admin_controller.rb index 5e912a5..f862b2f 100644 --- a/plugins/newsletter/controllers/newsletter_plugin_admin_controller.rb +++ b/plugins/newsletter/controllers/newsletter_plugin_admin_controller.rb @@ -26,7 +26,7 @@ class NewsletterPluginAdminController < PluginAdminController end end - @blogs = Blog.includes(:profile).find_all_by_id(@newsletter.blog_ids) + @blogs = Blog.includes(:profile).where id: @newsletter.blog_ids end #TODO: Make this query faster diff --git a/plugins/newsletter/lib/newsletter_plugin/newsletter.rb b/plugins/newsletter/lib/newsletter_plugin/newsletter.rb index be58ae6..4476d97 100644 --- a/plugins/newsletter/lib/newsletter_plugin/newsletter.rb +++ b/plugins/newsletter/lib/newsletter_plugin/newsletter.rb @@ -11,7 +11,7 @@ class NewsletterPlugin::Newsletter < ActiveRecord::Base attr_accessible :environment, :enabled, :periodicity, :subject, :posts_per_blog, :footer, :blog_ids, :additional_recipients, :person, :person_id, :moderated - scope :enabled, :conditions => { :enabled => true } + scope :enabled, -> { where enabled: true } # These methods are used by NewsletterMailing def people @@ -19,10 +19,9 @@ class NewsletterPlugin::Newsletter < ActiveRecord::Base if list.empty? environment.people else - environment.people.all( - :joins => "LEFT OUTER JOIN users ON (users.id = profiles.user_id)", - :conditions => "users.email NOT IN (#{list})" - ) + environment.people + .joins('LEFT OUTER JOIN users ON (users.id = profiles.user_id)') + .where("users.email NOT IN (#{list})") end end @@ -51,7 +50,7 @@ class NewsletterPlugin::Newsletter < ActiveRecord::Base validates_each :blog_ids do |record, attr, value| if record.environment - unless value.delete_if(&:zero?).select { |id| !Blog.find_by_id(id) || Blog.find(id).environment != record.environment }.empty? + unless value.delete_if(&:zero?).select { |id| !Blog.find_by(id: id) || Blog.find(id).environment != record.environment }.empty? record.errors.add(attr, _('must be valid')) end end @@ -82,9 +81,9 @@ class NewsletterPlugin::Newsletter < ActiveRecord::Base def posts(data = {}) limit = self.posts_per_blog.zero? ? nil : self.posts_per_blog posts = if self.last_send_at.nil? - self.blogs.map{|blog| blog.posts.all(:limit => limit)}.flatten + self.blogs.flat_map{ |blog| blog.posts.limit limit } else - self.blogs.map{|blog| blog.posts.where("published_at >= :last_send_at", {last_send_at: self.last_send_at}).all(:limit => limit)}.flatten + self.blogs.flat_map{ |blog| blog.posts.where("published_at >= :last_send_at", {last_send_at: self.last_send_at}).limit limit } end data[:post_ids].nil? ? posts : posts.select{|post| data[:post_ids].include?(post.id.to_s)} end @@ -171,9 +170,7 @@ class NewsletterPlugin::Newsletter < ActiveRecord::Base acts_as_having_image def last_send_at - last_mailing = NewsletterPlugin::NewsletterMailing.last( - :conditions => {:source_id => self.id} - ) + last_mailing = NewsletterPlugin::NewsletterMailing.where(source_id: self.id).last last_mailing.nil? ? nil : last_mailing.created_at end diff --git a/plugins/newsletter/test/functional/newsletter_plugin_admin_controller_test.rb b/plugins/newsletter/test/functional/newsletter_plugin_admin_controller_test.rb index 0216c23..f32c480 100644 --- a/plugins/newsletter/test/functional/newsletter_plugin_admin_controller_test.rb +++ b/plugins/newsletter/test/functional/newsletter_plugin_admin_controller_test.rb @@ -46,7 +46,7 @@ class NewsletterPluginAdminControllerTest < ActionController::TestCase post :index, :newsletter => { :enabled => 'true' } - newsletter = NewsletterPlugin::Newsletter.find_by_environment_id(@environment.id) + newsletter = NewsletterPlugin::Newsletter.find_by environment_id: @environment.id assert newsletter.enabled end @@ -56,7 +56,7 @@ class NewsletterPluginAdminControllerTest < ActionController::TestCase post :index, :newsletter => { :periodicity => '10' } - newsletter = NewsletterPlugin::Newsletter.find_by_environment_id(@environment.id) + newsletter = NewsletterPlugin::Newsletter.find_by environment_id: @environment.id assert_equal 10, newsletter.periodicity end diff --git a/plugins/newsletter/test/unit/newsletter_plugin_newsletter_test.rb b/plugins/newsletter/test/unit/newsletter_plugin_newsletter_test.rb index 58af2d1..031c781 100644 --- a/plugins/newsletter/test/unit/newsletter_plugin_newsletter_test.rb +++ b/plugins/newsletter/test/unit/newsletter_plugin_newsletter_test.rb @@ -56,7 +56,7 @@ class NewsletterPluginNewsletterTest < ActiveSupport::TestCase :periodicity => '3', :person => fast_create(Person)) - assert_equal 3, NewsletterPlugin::Newsletter.find_by_environment_id(environment.id).periodicity + assert_equal 3, NewsletterPlugin::Newsletter.find_by(environment_id: environment.id).periodicity end should 'save period as number only' do diff --git a/plugins/oauth_client/lib/oauth_client_plugin.rb b/plugins/oauth_client/lib/oauth_client_plugin.rb index 17d243a..d08738f 100644 --- a/plugins/oauth_client/lib/oauth_client_plugin.rb +++ b/plugins/oauth_client/lib/oauth_client_plugin.rb @@ -56,7 +56,7 @@ class OauthClientPlugin < Noosfero::Plugin strategy = env['omniauth.strategy'] Noosfero::MultiTenancy.setup!(request.host) - domain = Domain.find_by_name(request.host) + domain = Domain.by_name(request.host) environment = domain.environment rescue Environment.default provider_id = request.params['id'] diff --git a/plugins/oauth_provider/lib/oauth_provider_plugin.rb b/plugins/oauth_provider/lib/oauth_provider_plugin.rb index 2b7bc10..ebe6922 100644 --- a/plugins/oauth_provider/lib/oauth_provider_plugin.rb +++ b/plugins/oauth_provider/lib/oauth_provider_plugin.rb @@ -16,15 +16,15 @@ class OauthProviderPlugin < Noosfero::Plugin orm :active_record resource_owner_authenticator do - domain = Domain.find_by_name(request.host) + domain = Domain.by_name(request.host) environment = domain ? domain.environment : Environment.default - environment.users.find_by_id(session[:user]) || redirect_to('/account/login') + environment.users.find_by(id: session[:user]) || redirect_to('/account/login') end admin_authenticator do - domain = Domain.find_by_name(request.host) + domain = Domain.by_name(request.host) environment = domain ? domain.environment : Environment.default - user = environment.users.find_by_id(session[:user]) + user = environment.users.find_by id: session[:user] unless user && user.person.is_admin?(environment) redirect_to('/account/login') end diff --git a/plugins/orders/controllers/profile/orders_plugin_order_controller.rb b/plugins/orders/controllers/profile/orders_plugin_order_controller.rb index 606a186..42d3ed2 100644 --- a/plugins/orders/controllers/profile/orders_plugin_order_controller.rb +++ b/plugins/orders/controllers/profile/orders_plugin_order_controller.rb @@ -19,7 +19,7 @@ class OrdersPluginOrderController < ProfileController protected def load_order - @order = hmvc_orders_context::Sale.find_by_id params[:id] + @order = hmvc_orders_context::Sale.find_by id: params[:id] render_access_denied if @order.present? and (not @user_is_admin or not @order.may_view? user) end diff --git a/plugins/orders/controllers/public/orders_plugin_controller.rb b/plugins/orders/controllers/public/orders_plugin_controller.rb index 682a5fe..ae6c39a 100644 --- a/plugins/orders/controllers/public/orders_plugin_controller.rb +++ b/plugins/orders/controllers/public/orders_plugin_controller.rb @@ -14,7 +14,7 @@ class OrdersPluginController < PublicController def clear_orders_session return if user - previous_orders.update_all ['session_id = ?', nil] + previous_orders.update_all session_id: nil end protected diff --git a/plugins/orders/db/migrate/20140412202042_refactor_orders_plugin_statuses.rb b/plugins/orders/db/migrate/20140412202042_refactor_orders_plugin_statuses.rb index 82a3b12..04bf86b 100644 --- a/plugins/orders/db/migrate/20140412202042_refactor_orders_plugin_statuses.rb +++ b/plugins/orders/db/migrate/20140412202042_refactor_orders_plugin_statuses.rb @@ -38,7 +38,7 @@ class RefactorOrdersPluginStatuses < ActiveRecord::Migration add_column :orders_plugin_orders, :received_at, :datetime OrdersPlugin::Order.record_timestamps = false - OrdersPlugin::Order.update_all ["status = 'ordered'"], ["status = 'confirmed'"] + OrdersPlugin::Order.where(status: 'confirmed').update_all status: 'ordered' OrdersPlugin::Order.find_each do |order| order.ordered_at = order.updated_at if order.status == 'ordered' order.save run_callbacks: false diff --git a/plugins/orders/models/orders_plugin/item.rb b/plugins/orders/models/orders_plugin/item.rb index add5f13..0c94596 100644 --- a/plugins/orders/models/orders_plugin/item.rb +++ b/plugins/orders/models/orders_plugin/item.rb @@ -62,7 +62,7 @@ class OrdersPlugin::Item < ActiveRecord::Base scope :ordered, -> { joins(:order).where 'orders_plugin_orders.status = ?', 'ordered' } scope :for_product, -> (product) { where product_id: product.id } - default_scope include: [:product] + default_scope -> { includes :product } validate :has_order validates_presence_of :product diff --git a/plugins/orders/models/orders_plugin/order.rb b/plugins/orders/models/orders_plugin/order.rb index 72a0378..60e5714 100644 --- a/plugins/orders/models/orders_plugin/order.rb +++ b/plugins/orders/models/orders_plugin/order.rb @@ -68,7 +68,7 @@ class OrdersPlugin::Order < ActiveRecord::Base where cond end - scope :latest, order: 'created_at DESC' + scope :latest, -> { order 'created_at DESC' } scope :draft, -> { where status: 'draft' } scope :planned, -> { where status: 'planned' } diff --git a/plugins/orders_cycle/controllers/myprofile/orders_cycle_plugin_product_controller.rb b/plugins/orders_cycle/controllers/myprofile/orders_cycle_plugin_product_controller.rb index 2e5a10f..edcf2c9 100644 --- a/plugins/orders_cycle/controllers/myprofile/orders_cycle_plugin_product_controller.rb +++ b/plugins/orders_cycle/controllers/myprofile/orders_cycle_plugin_product_controller.rb @@ -18,7 +18,7 @@ class OrdersCyclePluginProductController < SuppliersPlugin::ProductController @offered_product = OrdersCyclePlugin::OfferedProduct.find params[:id] @order = OrdersCyclePlugin::Sale.find params[:order_id] raise 'Order confirmed or cycle is closed for orders' unless @order.open? - @item = @order.items.find_by_product_id @offered_product.id + @item = @order.items.find_by product_id: @offered_product.id @item.destroy rescue render nothing: true end diff --git a/plugins/orders_cycle/models/orders_cycle_plugin/cycle.rb b/plugins/orders_cycle/models/orders_cycle_plugin/cycle.rb index d6a1269..38638c1 100644 --- a/plugins/orders_cycle/models/orders_cycle_plugin/cycle.rb +++ b/plugins/orders_cycle/models/orders_cycle_plugin/cycle.rb @@ -245,7 +245,7 @@ class OrdersCyclePlugin::Cycle < ActiveRecord::Base end def add_products_job - @add_products_job ||= Delayed::Job.find_by_id self.data[:add_products_job_id] + @add_products_job ||= Delayed::Job.find_by id: self.data[:add_products_job_id] end protected diff --git a/plugins/organization_ratings/lib/ext/organization.rb b/plugins/organization_ratings/lib/ext/organization.rb index e9af89b..229274e 100644 --- a/plugins/organization_ratings/lib/ext/organization.rb +++ b/plugins/organization_ratings/lib/ext/organization.rb @@ -3,5 +3,5 @@ require_dependency 'organization' Organization.class_eval do has_many :organization_ratings - has_many :comments, :class_name => 'Comment', :foreign_key => 'source_id', :dependent => :destroy, :order => 'created_at asc' + has_many :comments, -> { order 'created_at asc' }, class_name: 'Comment', foreign_key: 'source_id', dependent: :destroy end diff --git a/plugins/people_block/lib/members_block.rb b/plugins/people_block/lib/members_block.rb index 9cee06b..942d64a 100644 --- a/plugins/people_block/lib/members_block.rb +++ b/plugins/people_block/lib/members_block.rb @@ -21,7 +21,7 @@ class MembersBlock < PeopleBlockBase end def role - visible_role && !visible_role.empty? ? Role.find_by_key_and_environment_id(visible_role, owner.environment) : nil + visible_role && !visible_role.empty? ? Role.find_by(key: visible_role, environment_id: owner.environment.id) : nil end def roles diff --git a/plugins/people_block/lib/people_block_base.rb b/plugins/people_block/lib/people_block_base.rb index 9b88a63..8943437 100644 --- a/plugins/people_block/lib/people_block_base.rb +++ b/plugins/people_block/lib/people_block_base.rb @@ -29,11 +29,11 @@ class PeopleBlockBase < Block result = nil visible_profiles = profiles.visible.includes([:image,:domains,:preferred_domain,:environment]) if !prioritize_profiles_with_image - result = visible_profiles.all(:limit => limit, :order => 'profiles.updated_at DESC').sort_by{ rand } + result = visible_profiles.limit(limit).order('profiles.updated_at DESC').sort_by{ rand } elsif profiles.visible.with_image.count >= limit - result = visible_profiles.with_image.all(:limit => limit * 5, :order => 'profiles.updated_at DESC').sort_by{ rand } + result = visible_profiles.with_image.limit(limit * 5).order('profiles.updated_at DESC').sort_by{ rand } else - result = visible_profiles.with_image.sort_by{ rand } + visible_profiles.without_image.all(:limit => limit * 5, :order => 'profiles.updated_at DESC').sort_by{ rand } + result = visible_profiles.with_image.sort_by{ rand } + visible_profiles.without_image.limit(limit * 5).order('profiles.updated_at DESC').sort_by{ rand } end result.slice(0..limit-1) end diff --git a/plugins/profile_members_headlines/lib/profile_members_headlines_block.rb b/plugins/profile_members_headlines/lib/profile_members_headlines_block.rb index 3ba31dc..c3d6c01 100644 --- a/plugins/profile_members_headlines/lib/profile_members_headlines_block.rb +++ b/plugins/profile_members_headlines/lib/profile_members_headlines_block.rb @@ -26,10 +26,13 @@ class ProfileMembersHeadlinesBlock < Block end def authors_list - result = owner.members_by_role(filtered_roles).is_public.includes([:image,:domains,:preferred_domain,:environment]).order('updated_at DESC') + result = owner + .members_by_role(filtered_roles) + .is_public + .includes([:image,:domains,:preferred_domain,:environment]).order('updated_at DESC') + .limit(limit * 5) - result.all(:limit => limit * 5).select { |p| p.has_headline? -}.slice(0..limit-1) + result.select{ |p| p.has_headline? }.slice(0..limit-1) end def content(args={}) diff --git a/plugins/shopping_cart/controllers/shopping_cart_plugin_controller.rb b/plugins/shopping_cart/controllers/shopping_cart_plugin_controller.rb index 305f7d4..9b28aba 100644 --- a/plugins/shopping_cart/controllers/shopping_cart_plugin_controller.rb +++ b/plugins/shopping_cart/controllers/shopping_cart_plugin_controller.rb @@ -353,7 +353,7 @@ class ShoppingCartPluginController < OrdersPluginController def products self.cart[:items].collect do |id, quantity| - product = Product.find_by_id(id) + product = Product.find_by id: id if product { id: product.id, name: product.name, diff --git a/plugins/shopping_cart/features/step_definitions/delivery_steps.rb b/plugins/shopping_cart/features/step_definitions/delivery_steps.rb index 452242c..a68ab66 100644 --- a/plugins/shopping_cart/features/step_definitions/delivery_steps.rb +++ b/plugins/shopping_cart/features/step_definitions/delivery_steps.rb @@ -1,5 +1,5 @@ Given /^"([^""]*)" has the following delivery methods$/ do |name, table| - enterprise = Enterprise.find_by_name(name) || Enterprise[name] + enterprise = Enterprise.find_by(name: name) || Enterprise[name] table.hashes.map{|item| item.dup}.each do |item| delivery_method = enterprise.delivery_methods.build delivery_method.update_attributes(item) diff --git a/plugins/shopping_cart/features/step_definitions/orders_steps.rb b/plugins/shopping_cart/features/step_definitions/orders_steps.rb index c73b05a..dbf759a 100644 --- a/plugins/shopping_cart/features/step_definitions/orders_steps.rb +++ b/plugins/shopping_cart/features/step_definitions/orders_steps.rb @@ -1,10 +1,10 @@ Given /^the following purchase from "([^""]*)" on "([^""]*)" that is "([^""]*)"$/ do |consumer_identifier, enterprise_identifier, status, table| - consumer = Person.find_by_name(consumer_identifier) || Person[consumer_identifier] - enterprise = Enterprise.find_by_name(enterprise_identifier) || Enterprise[enterprise_identifier] + consumer = Person.find_by(name: consumer_identifier) || Person[consumer_identifier] + enterprise = Enterprise.find_by(name: enterprise_identifier) || Enterprise[enterprise_identifier] order = OrdersPlugin::Purchase.new(:profile => enterprise, :consumer => consumer, :status => status) table.hashes.map{|item| item.dup}.each do |item| - product = enterprise.products.find_by_name item[:product] + product = enterprise.products.find_by name: item[:product] item = order.items.build({:product => product, :name => item[:product], :quantity_consumer_ordered => item[:quantity], :price => item[:price]}) item.order = order end diff --git a/plugins/shopping_cart/features/step_definitions/shopping_cart_steps.rb b/plugins/shopping_cart/features/step_definitions/shopping_cart_steps.rb index a25321c..038ca50 100644 --- a/plugins/shopping_cart/features/step_definitions/shopping_cart_steps.rb +++ b/plugins/shopping_cart/features/step_definitions/shopping_cart_steps.rb @@ -1,6 +1,6 @@ Given /^the shopping basket is (enabled|disabled) on "([^""]*)"$/ do |status, name| status = status == 'enabled' - enterprise = Enterprise.find_by_name(name) || Enterprise[name] + enterprise = Enterprise.find_by(name: name) || Enterprise[name] settings = enterprise.shopping_cart_settings({:enabled => status}) settings.save! end diff --git a/plugins/shopping_cart/lib/shopping_cart_plugin/line_item.rb b/plugins/shopping_cart/lib/shopping_cart_plugin/line_item.rb index 11309cf..e3d13f8 100644 --- a/plugins/shopping_cart/lib/shopping_cart_plugin/line_item.rb +++ b/plugins/shopping_cart/lib/shopping_cart_plugin/line_item.rb @@ -9,7 +9,7 @@ class ShoppingCartPlugin::LineItem end def product - @product ||= Product.find_by_id(product_id) + @product ||= Product.find_by id: product_id end def name diff --git a/plugins/sniffer/controllers/sniffer_plugin_myprofile_controller.rb b/plugins/sniffer/controllers/sniffer_plugin_myprofile_controller.rb index 262b949..3abae1e 100644 --- a/plugins/sniffer/controllers/sniffer_plugin_myprofile_controller.rb +++ b/plugins/sniffer/controllers/sniffer_plugin_myprofile_controller.rb @@ -94,7 +94,7 @@ class SnifferPluginMyprofileController < MyProfileController protected def fetch_profiles(products) - profiles = Profile.all conditions: {id: products.map { |p| target_profile_id(p) }} + profiles = Profile.where id: products.map{ |p| target_profile_id p } profiles_by_id = {} profiles.each do |p| p.sniffer_plugin_distance = Noosfero::GeoRef.dist(@profile.lat, @profile.lng, p.lat, p.lng) @@ -113,9 +113,9 @@ class SnifferPluginMyprofileController < MyProfileController id_profiles = fetch_profiles(data) - products = Product.all conditions: {id: grab_id.call('id')}, include: [:enterprise, :product_category] + products = Product.where(id: grab_id.call('id')).includes(:enterprise, :product_category) products.each{ |p| id_products[p.id] ||= p } - knowledges = Article.all conditions: {id: grab_id.call('knowledge_id')} + knowledges = Article.where(id: grab_id.call('knowledge_id')) knowledges.each{ |k| id_knowledges[k.id] ||= k} data.each do |attributes| diff --git a/plugins/sniffer/lib/ext/product.rb b/plugins/sniffer/lib/ext/product.rb index 85321f6..4d4ded3 100644 --- a/plugins/sniffer/lib/ext/product.rb +++ b/plugins/sniffer/lib/ext/product.rb @@ -11,19 +11,16 @@ class Product # - Enterprise 1 has Product A that uses input X # - Enterprise 2 has Product B that belongs to category X # -> Enterprise 1 as a parameter to this scope would return product B - scope :sniffer_plugin_suppliers_products, lambda { |enterprise| - { - select: "DISTINCT products_2.*, - 'product' as view", - joins: "INNER JOIN inputs ON ( products.id = inputs.product_id ) - INNER JOIN categories ON ( inputs.product_category_id = categories.id ) - INNER JOIN products products_2 ON ( categories.id = products_2.product_category_id ) - INNER JOIN profiles ON ( profiles.id = products_2.profile_id )", - conditions: "products.profile_id = #{enterprise.id} - AND profiles.public_profile = true AND profiles.visible = true - AND profiles.enabled = true - AND profiles.id <> #{enterprise.id}" - } + scope :sniffer_plugin_suppliers_products, -> enterprise { + select("DISTINCT products_2.*, 'product' as view") + .joins('INNER JOIN inputs ON products.id = inputs.product_id') + .joins('INNER JOIN categories ON inputs.product_category_id = categories.id') + .joins('INNER JOIN products products_2 ON categories.id = products_2.product_category_id') + .joins('INNER JOIN profiles ON profiles.id = products_2.profile_id') + .where("products.profile_id = #{enterprise.id}") + .where('profiles.public_profile = true AND profiles.visible = true') + .where('profiles.enabled = true') + .where("profiles.id <> #{enterprise.id}") } # inputs x products @@ -34,20 +31,16 @@ class Product # - Enterprise 2 has Product B that uses input X # -> Enterprise 1 as a parameter to this scope would return product A # with an extra column `consumer_profile_id` equal to Enterprise 2 id - scope :sniffer_plugin_consumers_products, lambda { |enterprise| - { - select: "DISTINCT products_2.*, - profiles.id as consumer_profile_id, - 'product' as view", - joins: "INNER JOIN inputs ON ( products.id = inputs.product_id ) - INNER JOIN categories ON ( inputs.product_category_id = categories.id ) - INNER JOIN products products_2 ON ( categories.id = products_2.product_category_id ) - INNER JOIN profiles ON ( profiles.id = products.profile_id )", - conditions: "products_2.profile_id = #{enterprise.id} - AND profiles.public_profile = true AND profiles.visible = true - AND profiles.enabled = true - AND profiles.id <> #{enterprise.id}" - } + scope :sniffer_plugin_consumers_products, -> enterprise { + select("DISTINCT products_2.*, profiles.id as consumer_profile_id, 'product' as view") + .joins('INNER JOIN inputs ON products.id = inputs.product_id') + .joins('INNER JOIN categories ON inputs.product_category_id = categories.id') + .joins('INNER JOIN products products_2 ON categories.id = products_2.product_category_id') + .joins('INNER JOIN profiles ON profiles.id = products.profile_id') + .where("products_2.profile_id = #{enterprise.id}") + .where('profiles.public_profile = true AND profiles.visible = true') + .where('profiles.enabled = true') + .where("profiles.id <> #{enterprise.id}") } # interest x products @@ -57,20 +50,17 @@ class Product # - Enterprise 1 has category X as a buyer interest # - Enterprise 2 has Product B that belongs to category X # -> Enterprise 1 as a parameter to this scope would return product B - scope :sniffer_plugin_interests_suppliers_products, lambda { |profile| - { - from: "profiles sniffer", - select: "DISTINCT products.*, - 'product' as view", - joins: "INNER JOIN sniffer_plugin_opportunities AS op ON ( sniffer.id = op.profile_id AND op.opportunity_type = 'ProductCategory' ) - INNER JOIN categories ON ( op.opportunity_id = categories.id ) - INNER JOIN products ON ( products.product_category_id = categories.id ) - INNER JOIN profiles ON ( products.profile_id = profiles.id )", - conditions: "sniffer.id = #{profile.id} AND products.profile_id <> #{profile.id} - AND profiles.public_profile = true AND profiles.visible = true - AND profiles.enabled = true - AND profiles.id <> #{profile.id}" - } + scope :sniffer_plugin_interests_suppliers_products, -> profile { + from("profiles sniffer") + .select("DISTINCT products.*, 'product' as view") + .joins("INNER JOIN sniffer_plugin_opportunities AS op ON sniffer.id = op.profile_id AND op.opportunity_type = 'ProductCategory'") + .joins('INNER JOIN categories ON op.opportunity_id = categories.id') + .joins('INNER JOIN products ON products.product_category_id = categories.id') + .joins('INNER JOIN profiles ON products.profile_id = profiles.id') + .where("sniffer.id = #{profile.id} AND products.profile_id <> #{profile.id}") + .where('profiles.public_profile = true AND profiles.visible = true') + .where('profiles.enabled = true') + .where("profiles.id <> #{profile.id}") } # products x interests @@ -81,97 +71,73 @@ class Product # - Enterprise 2 has category X as a buyer interest # -> Enterprise 1 as a parameter to this scope would return product A # with an extra column `consumer_profile_id` equal to Enterprise 2 id - scope :sniffer_plugin_interests_consumers_products, lambda { |profile| - { - select: "DISTINCT products.*, - profiles.id as consumer_profile_id, - 'product' as view", - joins: "INNER JOIN categories ON ( categories.id = products.product_category_id ) - INNER JOIN sniffer_plugin_opportunities as op ON ( categories.id = op.opportunity_id AND op.opportunity_type = 'ProductCategory' ) - INNER JOIN profiles ON ( op.profile_id = profiles.id )", - conditions: "products.profile_id = #{profile.id} - AND profiles.public_profile = true AND profiles.visible = true - AND profiles.enabled = true - AND profiles.id <> #{profile.id}" - } + scope :sniffer_plugin_interests_consumers_products, -> profile { + select("DISTINCT products.*, profiles.id as consumer_profile_id, 'product' as view") + .joins('INNER JOIN categories ON categories.id = products.product_category_id') + .joins("INNER JOIN sniffer_plugin_opportunities as op ON categories.id = op.opportunity_id AND op.opportunity_type = 'ProductCategory'") + .joins('INNER JOIN profiles ON op.profile_id = profiles.id') + .where("products.profile_id = #{profile.id}") + .where('profiles.public_profile = true AND profiles.visible = true') + .where('profiles.enabled = true') + .where("profiles.id <> #{profile.id}") } # knowledge x inputs - scope :sniffer_plugin_knowledge_consumers_inputs, lambda { |profile| - { - select: "DISTINCT products.*, - articles.id AS knowledge_id, - 'knowledge' as view", - joins: "INNER JOIN inputs ON ( products.id = inputs.product_id ) - INNER JOIN article_resources ON (article_resources.resource_id = inputs.product_category_id AND article_resources.resource_type = 'ProductCategory') - INNER JOIN articles ON (article_resources.article_id = articles.id) - INNER JOIN profiles ON ( products.profile_id = profiles.id )", - conditions: "articles.type = 'CmsLearningPlugin::Learning' - AND articles.profile_id = #{profile.id} - AND products.profile_id <> #{profile.id}" - } + scope :sniffer_plugin_knowledge_consumers_inputs, -> profile { + select("DISTINCT products.*, articles.id AS knowledge_id, 'knowledge' as view") + .joins('INNER JOIN inputs ON products.id = inputs.product_id') + .joins("INNER JOIN article_resources ON article_resources.resource_id = inputs.product_category_id AND article_resources.resource_type = 'ProductCategory'") + .joins('INNER JOIN articles ON article_resources.article_id = articles.id') + .joins('INNER JOIN profiles ON products.profile_id = profiles.id') + .where("articles.type = 'CmsLearningPlugin::Learning'") + .where("articles.profile_id = #{profile.id}") + .where("products.profile_id <> #{profile.id}") } # inputs x knowledge - scope :sniffer_plugin_knowledge_suppliers_inputs, lambda { |profile| - { - select: "DISTINCT products.*, - profiles.id as supplier_profile_id, articles.id AS knowledge_id, - 'knowledge' as view", - joins: "INNER JOIN inputs ON ( products.id = inputs.product_id ) - INNER JOIN article_resources ON (article_resources.resource_id = inputs.product_category_id AND article_resources.resource_type = 'ProductCategory') - INNER JOIN articles ON (article_resources.article_id = articles.id) - INNER JOIN profiles ON ( articles.profile_id = profiles.id )", - conditions: "articles.type = 'CmsLearningPlugin::Learning' - AND articles.profile_id <> #{profile.id} - AND products.profile_id = #{profile.id}" - } + scope :sniffer_plugin_knowledge_suppliers_inputs, -> profile { + select("DISTINCT products.*, profiles.id as supplier_profile_id, articles.id AS knowledge_id, 'knowledge' as view") + .joins("INNER JOIN inputs ON products.id = inputs.product_id") + .joins("INNER JOIN article_resources ON article_resources.resource_id = inputs.product_category_id AND article_resources.resource_type = 'ProductCategory'") + .joins('INNER JOIN articles ON article_resources.article_id = articles.id') + .joins('INNER JOIN profiles ON articles.profile_id = profiles.id') + .where("articles.type = 'CmsLearningPlugin::Learning'") + .where("articles.profile_id <> #{profile.id}") + .where("products.profile_id = #{profile.id}") } # knowledge x interests - scope :sniffer_plugin_knowledge_consumers_interests, lambda { |profile| - { - select: "DISTINCT articles.id AS knowledge_id, - op.opportunity_id AS product_category_id, - profiles.id as profile_id, - 'knowledge' as view", - from: "articles", - joins: "INNER JOIN article_resources ON (articles.id = article_resources.article_id) - INNER JOIN sniffer_plugin_opportunities as op ON ( article_resources.resource_id = op.opportunity_id AND op.opportunity_type = 'ProductCategory' AND article_resources.resource_type = 'ProductCategory' ) - INNER JOIN profiles ON ( op.profile_id = profiles.id )", - conditions: "articles.profile_id = #{profile.id} - AND profiles.public_profile = true - AND profiles.visible = true - AND profiles.enabled = true - AND profiles.id <> #{profile.id}" - } + scope :sniffer_plugin_knowledge_consumers_interests, -> profile { + from('articles') + .select("DISTINCT articles.id AS knowledge_id, op.opportunity_id AS product_category_id, profiles.id as profile_id, 'knowledge' as view") + .joins('INNER JOIN article_resources ON articles.id = article_resources.article_id') + .joins("INNER JOIN sniffer_plugin_opportunities as op ON article_resources.resource_id = op.opportunity_id AND op.opportunity_type = 'ProductCategory' AND article_resources.resource_type = 'ProductCategory'") + .joins('INNER JOIN profiles ON op.profile_id = profiles.id') + .where("articles.profile_id = #{profile.id}") + .where('profiles.public_profile = true') + .where('profiles.visible = true') + .where('profiles.enabled = true') + .where("profiles.id <> #{profile.id}") } # interests x knowledge - scope :sniffer_plugin_knowledge_suppliers_interests, lambda { |profile| - { - select: "DISTINCT articles.id AS knowledge_id, - op.opportunity_id AS product_category_id, - profiles.id as profile_id, - 'knowledge' as view", - from: "articles", - joins: "INNER JOIN article_resources ON (articles.id = article_resources.article_id) - INNER JOIN sniffer_plugin_opportunities as op ON ( article_resources.resource_id = op.opportunity_id AND op.opportunity_type = 'ProductCategory' AND article_resources.resource_type = 'ProductCategory' ) - INNER JOIN profiles ON ( articles.profile_id = profiles.id )", - conditions: "articles.profile_id <> #{profile.id} - AND profiles.public_profile = true - AND profiles.visible = true - AND profiles.enabled = true - AND profiles.id = #{profile.id}" - } + scope :sniffer_plugin_knowledge_suppliers_interests, -> profile { + from('articles') + .select("DISTINCT articles.id AS knowledge_id, op.opportunity_id AS product_category_id, profiles.id as profile_id, 'knowledge' as view") + .joins('INNER JOIN article_resources ON articles.id = article_resources.article_id') + .joins("INNER JOIN sniffer_plugin_opportunities as op ON article_resources.resource_id = op.opportunity_id AND op.opportunity_type = 'ProductCategory' AND article_resources.resource_type = 'ProductCategory'") + .joins('INNER JOIN profiles ON articles.profile_id = profiles.id') + .where("articles.profile_id <> #{profile.id}") + .where('profiles.public_profile = true') + .where('profiles.visible = true') + .where('profiles.enabled = true') + .where("profiles.id = #{profile.id}") } # searches for products as supplies for a given product category - scope :sniffer_plugin_products_from_category, lambda { |product_category| - { - conditions: { product_category_id: product_category.id }, - select: "*, 'product' as view" - } + scope :sniffer_plugin_products_from_category, -> product_category { + select("*, 'product' as view") + .where(product_category_id: product_category.id) } end diff --git a/plugins/sniffer/lib/ext/product_category.rb b/plugins/sniffer/lib/ext/product_category.rb index 857578d..5d70bdd 100644 --- a/plugins/sniffer/lib/ext/product_category.rb +++ b/plugins/sniffer/lib/ext/product_category.rb @@ -1,5 +1,8 @@ require_dependency 'product_category' class ProductCategory - has_many :sniffer_plugin_enterprises, :through => :products, :source => :enterprise, :uniq => true + + has_many :sniffer_plugin_enterprises, -> { distinct }, + through: :products, source: :enterprise + end diff --git a/plugins/sniffer/lib/ext/profile.rb b/plugins/sniffer/lib/ext/profile.rb index 0b287b0..c73efec 100644 --- a/plugins/sniffer/lib/ext/profile.rb +++ b/plugins/sniffer/lib/ext/profile.rb @@ -4,9 +4,10 @@ class Profile attr_accessor :sniffer_plugin_distance - has_many :sniffer_opportunities, :class_name => 'SnifferPlugin::Opportunity', :dependent => :destroy - has_many :sniffer_interested_product_categories, :through => :sniffer_opportunities, :source => :product_category, :class_name => 'ProductCategory', - :conditions => ['sniffer_plugin_opportunities.opportunity_type = ?', 'ProductCategory'] + has_many :sniffer_opportunities, class_name: 'SnifferPlugin::Opportunity', dependent: :destroy + has_many :sniffer_interested_product_categories, -> { + where 'sniffer_plugin_opportunities.opportunity_type = ?', 'ProductCategory' + }, through: :sniffer_opportunities, source: :product_category, class_name: 'ProductCategory' attr_accessor :sniffer_interested_product_category_string_ids descendants.each do |k| @@ -31,11 +32,11 @@ class Profile def sniffer_suppliers_products products = [] - products += Product.sniffer_plugin_suppliers_products self if self.enterprise? - products += Product.sniffer_plugin_interests_suppliers_products self + products.concat Product.sniffer_plugin_suppliers_products self if self.enterprise? + products.concat Product.sniffer_plugin_interests_suppliers_products self if defined?(CmsLearningPlugin) - products += Product.sniffer_plugin_knowledge_suppliers_inputs self - products += Product.sniffer_plugin_knowledge_suppliers_interests self + products.concat Product.sniffer_plugin_knowledge_suppliers_inputs self + products.concat Product.sniffer_plugin_knowledge_suppliers_interests self end products @@ -44,11 +45,11 @@ class Profile def sniffer_consumers_products products = [] - products += Product.sniffer_plugin_consumers_products self if self.enterprise? - products += Product.sniffer_plugin_interests_consumers_products self + products.concat Product.sniffer_plugin_consumers_products self if self.enterprise? + products.concat Product.sniffer_plugin_interests_consumers_products self if defined?(CmsLearningPlugin) - products += Product.sniffer_plugin_knowledge_consumers_inputs self - products += Product.sniffer_plugin_knowledge_consumers_interests self + products.concat Product.sniffer_plugin_knowledge_consumers_inputs self + products.concat Product.sniffer_plugin_knowledge_consumers_interests self end products diff --git a/plugins/sniffer/lib/sniffer_plugin/interests_block.rb b/plugins/sniffer/lib/sniffer_plugin/interests_block.rb index 17dda5c..5fdeee4 100644 --- a/plugins/sniffer/lib/sniffer_plugin/interests_block.rb +++ b/plugins/sniffer/lib/sniffer_plugin/interests_block.rb @@ -24,8 +24,8 @@ class SnifferPlugin::InterestsBlock < Block interests = profile.snnifer_opportunities interests |= profile.inputs if sniffer.profile.enterprise? else # Environment - interests = SnifferPlugin::Opportunity.product_categories :limit => 5, :order => 'created_at DESC' - interests += Input.all :limit => 5, :order => 'created_at DESC' + interests = SnifferPlugin::Opportunity.product_categories.limit(5).order('created_at DESC').all + interests += Input.limit(5).order('created_at DESC').all interests.sort{ |a, b| -1 * a.created_at.to_i <=> b.created_at.to_i } end diff --git a/plugins/sniffer/models/sniffer_plugin/opportunity.rb b/plugins/sniffer/models/sniffer_plugin/opportunity.rb index 26b44e8..e5916f9 100644 --- a/plugins/sniffer/models/sniffer_plugin/opportunity.rb +++ b/plugins/sniffer/models/sniffer_plugin/opportunity.rb @@ -7,15 +7,17 @@ class SnifferPlugin::Opportunity < ActiveRecord::Base belongs_to :opportunity, polymorphic: true # for has_many :through - belongs_to :product_category, class_name: 'ProductCategory', foreign_key: :opportunity_id, - conditions: ['sniffer_plugin_opportunities.opportunity_type = ?', 'ProductCategory'] + belongs_to :product_category, -> { + where 'sniffer_plugin_opportunities.opportunity_type = ?', 'ProductCategory' + }, class_name: 'ProductCategory', foreign_key: :opportunity_id + # getter def product_category opportunity_type == 'ProductCategory' ? opportunity : nil end - scope :product_categories, { - conditions: ['sniffer_plugin_opportunities.opportunity_type = ?', 'ProductCategory'] + scope :product_categories, -> { + where 'sniffer_plugin_opportunities.opportunity_type = ?', 'ProductCategory' } if defined? SolrPlugin diff --git a/plugins/solr/features/step_definitions/solr_steps.rb b/plugins/solr/features/step_definitions/solr_steps.rb index dcde964..d552610 100644 --- a/plugins/solr/features/step_definitions/solr_steps.rb +++ b/plugins/solr/features/step_definitions/solr_steps.rb @@ -6,7 +6,7 @@ end Given /^the following categories as facets$/ do |table| ids = [] table.hashes.each do |item| - cat = Category.find_by_name(item[:name]) + cat = Category.find_by name: item[:name] if cat.nil? cat = Category.create!(:environment_id => Environment.default.id, :name => item[:name]) end diff --git a/plugins/solr/lib/ext/product.rb b/plugins/solr/lib/ext/product.rb index b1cd209..44a6bb7 100644 --- a/plugins/solr/lib/ext/product.rb +++ b/plugins/solr/lib/ext/product.rb @@ -68,8 +68,8 @@ class Product def self.solr_plugin_f_qualifier_proc(ids) array = ids.split - qualifier = Qualifier.find_by_id array[0] - certifier = Certifier.find_by_id array[1] + qualifier = Qualifier.find_by id: array[0] + certifier = Certifier.find_by id: array[1] certifier ? [qualifier.name, _(' cert. ') + certifier.name] : qualifier.name end diff --git a/plugins/solr/vendor/plugins/acts_as_solr_reloaded/test/functional/acts_as_solr_test.rb b/plugins/solr/vendor/plugins/acts_as_solr_reloaded/test/functional/acts_as_solr_test.rb index da8f918..2bce8f4 100644 --- a/plugins/solr/vendor/plugins/acts_as_solr_reloaded/test/functional/acts_as_solr_test.rb +++ b/plugins/solr/vendor/plugins/acts_as_solr_reloaded/test/functional/acts_as_solr_test.rb @@ -4,7 +4,7 @@ require "#{File.dirname(File.expand_path(__FILE__))}/../test_helper" class ActsAsSolrTest < Test::Unit::TestCase fixtures :books, :movies, :electronics, :postings, :authors, :advertises - + MongoMapper.connection = Mongo::Connection.new("127.0.0.1", 27017, :slave_ok => true, :pool_size => 16, :timeout => 10) MongoMapper.database = "#mydb_test" Document.destroy_all @@ -197,7 +197,7 @@ class ActsAsSolrTest < Test::Unit::TestCase def test_rebuild_solr_index assert_equal 1, Book.count_by_solr('splinter') - Book.find(:first).solr_destroy + Book.first.solr_destroy assert_equal 0, Book.count_by_solr('splinter') Book.rebuild_solr_index @@ -210,10 +210,10 @@ class ActsAsSolrTest < Test::Unit::TestCase def test_solr_save_and_solr_destroy assert_equal 1, Book.count_by_solr('splinter') - Book.find(:first).solr_destroy + Book.first.solr_destroy assert_equal 0, Book.count_by_solr('splinter') - Book.find(:first).solr_save + Book.first.solr_save assert_equal 1, Book.count_by_solr('splinter') end @@ -322,7 +322,7 @@ class ActsAsSolrTest < Test::Unit::TestCase # to rebuild_solr_index def test_using_rebuild_solr_index_with_batch assert_equal 2, Movie.count_by_solr('office OR napoleon') - Movie.find(:all).each(&:solr_destroy) + Movie.all.each(&:solr_destroy) assert_equal 0, Movie.count_by_solr('office OR napoleon') Movie.rebuild_solr_index 100 @@ -454,7 +454,7 @@ class ActsAsSolrTest < Test::Unit::TestCase expected = {"name"=>["Ruby for Dummies"]} assert_equal expected, records.highlights.values.first end - + def test_spellcheck assert_equal "ruby for dummies", Book.search("rubi for dumies").suggest end diff --git a/plugins/solr/vendor/plugins/acts_as_solr_reloaded/test/test_helper.rb b/plugins/solr/vendor/plugins/acts_as_solr_reloaded/test/test_helper.rb index e776be4..0facf9d 100644 --- a/plugins/solr/vendor/plugins/acts_as_solr_reloaded/test/test_helper.rb +++ b/plugins/solr/vendor/plugins/acts_as_solr_reloaded/test/test_helper.rb @@ -58,7 +58,7 @@ class Test::Unit::TestCase table_names.each do |table_name| clear_from_solr(table_name) klass = instance_eval table_name.to_s.capitalize.singularize - klass.find(:all).each{|content| content.solr_save} + klass.all.each{|content| content.solr_save} end clear_from_solr(:novels) diff --git a/plugins/stoa/controllers/stoa_plugin_controller.rb b/plugins/stoa/controllers/stoa_plugin_controller.rb index b3a15d7..8d33749 100644 --- a/plugins/stoa/controllers/stoa_plugin_controller.rb +++ b/plugins/stoa/controllers/stoa_plugin_controller.rb @@ -28,7 +28,7 @@ class StoaPluginController < PublicController def check_usp_id begin - render :text => { :exists => StoaPlugin::UspUser.exists?(params[:usp_id]) && Person.find_by_usp_id(params[:usp_id]).nil? }.to_json + render :text => { :exists => StoaPlugin::UspUser.exists?(params[:usp_id]) && Person.find_by(usp_id: params[:usp_id]).nil? }.to_json rescue Exception => exception render :text => { :exists => false, :error => {:message => exception.to_s, :backtrace => exception.backtrace} }.to_json end @@ -36,7 +36,7 @@ class StoaPluginController < PublicController def check_cpf begin - render :text => { :exists => StoaPlugin::UspUser.find_by_codpes(params[:usp_id]).cpf.present? }.to_json + render :text => { :exists => StoaPlugin::UspUser.find_by(codpes: params[:usp_id]).cpf.present? }.to_json rescue Exception => exception render :text => { :exists => false, :error => {:message => exception.to_s, :backtrace => exception.backtrace} }.to_json end diff --git a/plugins/stoa/lib/ext/profile_suggestion.rb b/plugins/stoa/lib/ext/profile_suggestion.rb index ab50b84..8f1ab5d 100644 --- a/plugins/stoa/lib/ext/profile_suggestion.rb +++ b/plugins/stoa/lib/ext/profile_suggestion.rb @@ -14,8 +14,8 @@ class ProfileSuggestion StoaPlugin::UspAlunoTurmaGrad.classrooms_from_person(usp_id).each do |classroom| person_attempts += 1 return unless person.profile_suggestions.count < N_SUGGESTIONS && person_attempts < MAX_ATTEMPTS - StoaPlugin::UspAlunoTurmaGrad.find_all_by_codtur(classroom.codtur).each do |same_class| - classmate = Person.find_by_usp_id(same_class.codpes) + StoaPlugin::UspAlunoTurmaGrad.where(codtur: classroom.codtur).each do |same_class| + classmate = Person.find_by usp_id: same_class.codpes unless classmate.nil? || classmate == person || classmate.is_a_friend?(person) || person.already_request_friendship?(classmate) suggestion = person.profile_suggestions.find_or_initialize_by_suggestion_id(classmate.id) suggestion.common_classroom = 1 diff --git a/plugins/stoa/lib/stoa_plugin.rb b/plugins/stoa/lib/stoa_plugin.rb index 52069a7..db30a5e 100644 --- a/plugins/stoa/lib/stoa_plugin.rb +++ b/plugins/stoa/lib/stoa_plugin.rb @@ -50,7 +50,7 @@ class StoaPlugin < Noosfero::Plugin end def alternative_authentication - person = Person.find_by_usp_id(context.params[:usp_id_login]) + person = Person.find_by usp_id: context.params[:usp_id_login] if person user = User.authenticate(person.user.login, context.params[:password]) else diff --git a/plugins/stoa/lib/stoa_plugin/auth.rb b/plugins/stoa/lib/stoa_plugin/auth.rb index fa4ee67..5b2aa89 100644 --- a/plugins/stoa/lib/stoa_plugin/auth.rb +++ b/plugins/stoa/lib/stoa_plugin/auth.rb @@ -8,13 +8,13 @@ class StoaPlugin::Auth < Sinatra::Base post '/' do headers['Content-Type'] = 'application/json' if params[:login].blank? - person = Person.find_by_usp_id(params[:usp_id]) + person = Person.find_by usp_id: params[:usp_id] login = person ? person.user.login : nil else login = params[:login] end - domain = Domain.find_by_name(request.host) + domain = Domain.by_name(request.host) environment = domain && domain.environment environment ||= Environment.default diff --git a/plugins/stoa/lib/stoa_plugin/person_api.rb b/plugins/stoa/lib/stoa_plugin/person_api.rb index fa044fc..2ea7bc4 100644 --- a/plugins/stoa/lib/stoa_plugin/person_api.rb +++ b/plugins/stoa/lib/stoa_plugin/person_api.rb @@ -28,7 +28,7 @@ class StoaPlugin::PersonApi < Noosfero::FieldsDecorator end def tags - articles.published.tag_counts({:order => 'count desc', :limit => 10}).inject({}) do |memo,tag| + articles.published.tag_counts.order('count desc').limit(10).inject({}) do |memo,tag| memo[tag.name] = tag.count memo end diff --git a/plugins/stoa/lib/stoa_plugin/usp_aluno_turma_grad.rb b/plugins/stoa/lib/stoa_plugin/usp_aluno_turma_grad.rb index 1ac7b70..a5c362f 100644 --- a/plugins/stoa/lib/stoa_plugin/usp_aluno_turma_grad.rb +++ b/plugins/stoa/lib/stoa_plugin/usp_aluno_turma_grad.rb @@ -5,11 +5,11 @@ class StoaPlugin::UspAlunoTurmaGrad < ActiveRecord::Base self.table_name = :alunoturma_gr def self.exists?(usp_id) - StoaPlugin::UspUser.find_by_codpes(usp_id.to_i) + StoaPlugin::UspUser.find_by codpes: usp_id.to_i end def self.classrooms_from_person(usp_id) - StoaPlugin::UspAlunoTurmaGrad.find_all_by_codpes(usp_id) + StoaPlugin::UspAlunoTurmaGrad.where codpes: usp_id end end diff --git a/plugins/stoa/lib/stoa_plugin/usp_user.rb b/plugins/stoa/lib/stoa_plugin/usp_user.rb index 4a55602..e841a14 100644 --- a/plugins/stoa/lib/stoa_plugin/usp_user.rb +++ b/plugins/stoa/lib/stoa_plugin/usp_user.rb @@ -9,12 +9,12 @@ class StoaPlugin::UspUser < ActiveRecord::Base alias_attribute :birth_date, :dtanas def self.exists?(usp_id) - StoaPlugin::UspUser.find_by_codpes(usp_id.to_i) + StoaPlugin::UspUser.find_by codpes: usp_id.to_i end def self.matches?(usp_id, field, value) usp_id.to_s.gsub!(/[.-]/,'') - user = StoaPlugin::UspUser.find_by_codpes(usp_id.to_i) + user = StoaPlugin::UspUser.find_by codpes: usp_id.to_i return false if user.nil? || field.blank? || !user.respond_to?(field) || value.blank? case field.to_sym when :cpf diff --git a/plugins/stoa/test/functional/stoa_plugin_controller_test.rb b/plugins/stoa/test/functional/stoa_plugin_controller_test.rb index 5388377..dd842cb 100644 --- a/plugins/stoa/test/functional/stoa_plugin_controller_test.rb +++ b/plugins/stoa/test/functional/stoa_plugin_controller_test.rb @@ -157,7 +157,7 @@ class StoaPluginControllerTest < ActionController::TestCase usp_id = '12345678' user = mock user.stubs(:cpf).returns('12345678') - StoaPlugin::UspUser.stubs(:find_by_codpes).with(usp_id).returns(user) + StoaPlugin::UspUser.stubs(:find_by).with(codpes: usp_id).returns(user) get :check_cpf, :usp_id => usp_id assert json_response['exists'] end @@ -166,12 +166,12 @@ class StoaPluginControllerTest < ActionController::TestCase usp_id_with_cpf = '12345678' user_with_cpf = mock user_with_cpf.stubs(:cpf).returns('12345678') - StoaPlugin::UspUser.stubs(:find_by_codpes).with(usp_id_with_cpf).returns(user_with_cpf) + StoaPlugin::UspUser.stubs(:find_by).with(codpes: usp_id_with_cpf).returns(user_with_cpf) get :check_cpf, :usp_id => usp_id_with_cpf usp_id_without_cpf = '87654321' user_without_cpf = mock user_with_cpf.stubs(:cpf).returns(nil) - StoaPlugin::UspUser.stubs(:find_by_codpes).with(usp_id_without_cpf).returns(user_without_cpf) + StoaPlugin::UspUser.stubs(:find_by).with(codpes: usp_id_without_cpf).returns(user_without_cpf) get :check_cpf, :usp_id => usp_id_without_cpf refute json_response['exists'] end diff --git a/plugins/sub_organizations/features/step_definitions/sub_organizations_block_steps.rb b/plugins/sub_organizations/features/step_definitions/sub_organizations_block_steps.rb index 2ebcf54..2405ad1 100644 --- a/plugins/sub_organizations/features/step_definitions/sub_organizations_block_steps.rb +++ b/plugins/sub_organizations/features/step_definitions/sub_organizations_block_steps.rb @@ -1,6 +1,6 @@ Given /^"([^\"]*)" is a sub organization of "([^\"]*)"$/ do |child, parent| - child = Organization.find_by_name(child) || Organization[child] - parent = Organization.find_by_name(parent) || Organization[parent] + child = Organization.find_by(name: child) || Organization[child] + parent = Organization.find_by(name: parent) || Organization[parent] SubOrganizationsPlugin::Relation.add_children(parent, child) end diff --git a/plugins/sub_organizations/lib/sub_organizations_plugin.rb b/plugins/sub_organizations/lib/sub_organizations_plugin.rb index b76eb30..55e928a 100644 --- a/plugins/sub_organizations/lib/sub_organizations_plugin.rb +++ b/plugins/sub_organizations/lib/sub_organizations_plugin.rb @@ -56,7 +56,7 @@ class SubOrganizationsPlugin < Noosfero::Plugin end def self.limit(organizations) - organizations.all(:limit => DISPLAY_LIMIT, :order => 'updated_at DESC').sort_by{ rand } + organizations.limit(DISPLAY_LIMIT).order('updated_at DESC').sort_by{ rand } end def self.extra_blocks diff --git a/plugins/suppliers/db/migrate/20130902115916_add_active_to_suppliers_plugin_supplier.rb b/plugins/suppliers/db/migrate/20130902115916_add_active_to_suppliers_plugin_supplier.rb index 08af3e1..2b9baf4 100644 --- a/plugins/suppliers/db/migrate/20130902115916_add_active_to_suppliers_plugin_supplier.rb +++ b/plugins/suppliers/db/migrate/20130902115916_add_active_to_suppliers_plugin_supplier.rb @@ -3,8 +3,8 @@ end class AddActiveToSuppliersPluginSupplier < ActiveRecord::Migration def self.up - add_column :suppliers_plugin_suppliers, :active, :boolean, :default => true - SuppliersPlugin::Supplier.update_all ['active = ?', true] + add_column :suppliers_plugin_suppliers, :active, :boolean, default: true + SuppliersPlugin::Supplier.update_all active: true end def self.down diff --git a/plugins/suppliers/lib/ext/profile.rb b/plugins/suppliers/lib/ext/profile.rb index 5092560..8d20d37 100644 --- a/plugins/suppliers/lib/ext/profile.rb +++ b/plugins/suppliers/lib/ext/profile.rb @@ -24,10 +24,14 @@ subclass.class_eval do has_many :from_products, through: :products has_many :to_products, through: :products - has_many :suppliers, class_name: 'SuppliersPlugin::Supplier', foreign_key: :consumer_id, dependent: :destroy, - include: [{profile: [:domains], consumer: [:domains]}], order: 'name ASC' - has_many :consumers, class_name: 'SuppliersPlugin::Consumer', foreign_key: :profile_id, dependent: :destroy, - include: [{profile: [:domains], consumer: [:domains]}], order: 'name ASC' + has_many :suppliers, -> { + includes(profile: [:domains], consumer: [:domains]) + .order('name ASC') + }, class_name: 'SuppliersPlugin::Supplier', foreign_key: :consumer_id, dependent: :destroy + has_many :consumers, -> { + includes(profile: [:domains], consumer: [:domains]) + .order('name ASC') + }, class_name: 'SuppliersPlugin::Consumer', foreign_key: :profile_id, dependent: :destroy end end diff --git a/plugins/suppliers/lib/suppliers_plugin/import.rb b/plugins/suppliers/lib/suppliers_plugin/import.rb index 590593b..32f3a17 100644 --- a/plugins/suppliers/lib/suppliers_plugin/import.rb +++ b/plugins/suppliers/lib/suppliers_plugin/import.rb @@ -22,7 +22,7 @@ class SuppliersPlugin::Import end def self.products consumer, csv - default_product_category = consumer.environment.product_categories.find_by_name 'Produtos' + default_product_category = consumer.environment.product_categories.find_by name: 'Produtos' detection = CharlockHolmes::EncodingDetector.detect csv csv = CharlockHolmes::Converter.convert csv, detection[:encoding], 'UTF-8' diff --git a/plugins/suppliers/models/suppliers_plugin/base_product.rb b/plugins/suppliers/models/suppliers_plugin/base_product.rb index 4d76305..7bf5c76 100644 --- a/plugins/suppliers/models/suppliers_plugin/base_product.rb +++ b/plugins/suppliers/models/suppliers_plugin/base_product.rb @@ -7,17 +7,15 @@ class SuppliersPlugin::BaseProduct < Product accepts_nested_attributes_for :supplier_product - default_scope include: [ - # from_products is required for products.available - :from_products, - # FIXME: move use cases to a scope called 'includes_for_links' - { - suppliers: [{ profile: [:domains, {environment: :domains}] }] - }, - { - profile: [:domains, {environment: :domains}] - } - ] + default_scope -> { + includes( + # from_products is required for products.available + :from_products, + # FIXME: move use cases to a scope called 'includes_for_links' + {suppliers: [{ profile: [:domains, {environment: :domains}] }]}, + {profile: [:domains, {environment: :domains}]} + ) + } # if abstract_class is true then it will trigger https://github.com/rails/rails/issues/20871 #self.abstract_class = true diff --git a/plugins/suppliers/models/suppliers_plugin/source_product.rb b/plugins/suppliers/models/suppliers_plugin/source_product.rb index be90f1a..23d9c5d 100644 --- a/plugins/suppliers/models/suppliers_plugin/source_product.rb +++ b/plugins/suppliers/models/suppliers_plugin/source_product.rb @@ -2,7 +2,7 @@ class SuppliersPlugin::SourceProduct < ActiveRecord::Base attr_accessible :from_product, :to_product, :quantity - default_scope include: [:from_product, :to_product] + default_scope -> { includes :from_product, :to_product } belongs_to :from_product, class_name: 'Product' belongs_to :to_product, class_name: 'Product' diff --git a/plugins/tolerance_time/controllers/tolerance_time_plugin_myprofile_controller.rb b/plugins/tolerance_time/controllers/tolerance_time_plugin_myprofile_controller.rb index 1ee780a..57401cb 100644 --- a/plugins/tolerance_time/controllers/tolerance_time_plugin_myprofile_controller.rb +++ b/plugins/tolerance_time/controllers/tolerance_time_plugin_myprofile_controller.rb @@ -1,6 +1,6 @@ class ToleranceTimePluginMyprofileController < MyProfileController def index - @tolerance = ToleranceTimePlugin::Tolerance.find_by_profile_id(profile.id) || ToleranceTimePlugin::Tolerance.create!(:profile => profile) + @tolerance = ToleranceTimePlugin::Tolerance.find_by(profile_id: profile.id) || ToleranceTimePlugin::Tolerance.create!(:profile => profile) convert_values if request.post? begin diff --git a/plugins/tolerance_time/lib/ext/article.rb b/plugins/tolerance_time/lib/ext/article.rb index 8c47799..290b6e1 100644 --- a/plugins/tolerance_time/lib/ext/article.rb +++ b/plugins/tolerance_time/lib/ext/article.rb @@ -10,14 +10,14 @@ class Article if article.published ToleranceTimePlugin::Publication.create!(:target => article) else - publication = ToleranceTimePlugin::Publication.find_by_target(article) + publication = ToleranceTimePlugin::Publication.find_by target: article publication.destroy if publication.present? end end end before_destroy do |article| - publication = ToleranceTimePlugin::Publication.find_by_target(article) + publication = ToleranceTimePlugin::Publication.find_by target: article publication.destroy if publication.present? end end diff --git a/plugins/tolerance_time/lib/ext/comment.rb b/plugins/tolerance_time/lib/ext/comment.rb index ff64c05..4047516 100644 --- a/plugins/tolerance_time/lib/ext/comment.rb +++ b/plugins/tolerance_time/lib/ext/comment.rb @@ -6,7 +6,7 @@ class Comment end before_destroy do |comment| - publication = ToleranceTimePlugin::Publication.find_by_target(comment) + publication = ToleranceTimePlugin::Publication.find_by target: comment publication.destroy if publication.present? end end diff --git a/plugins/tolerance_time/lib/tolerance_time_plugin.rb b/plugins/tolerance_time/lib/tolerance_time_plugin.rb index 920a52e..29c6c36 100644 --- a/plugins/tolerance_time/lib/tolerance_time_plugin.rb +++ b/plugins/tolerance_time/lib/tolerance_time_plugin.rb @@ -12,7 +12,7 @@ class ToleranceTimePlugin < Noosfero::Plugin return false if content.kind_of?(Comment) && !content.article.kind_of?(Article) expirable = content.kind_of?(Comment) || (!content.folder? && content.published?) - publication = ToleranceTimePlugin::Publication.find_by_target(content) + publication = ToleranceTimePlugin::Publication.find_by target: content publication = ToleranceTimePlugin::Publication.create!(:target => content) if expirable && publication.nil? person_article = content.kind_of?(Article) && content.profile.kind_of?(Person) diff --git a/plugins/tolerance_time/lib/tolerance_time_plugin/publication.rb b/plugins/tolerance_time/lib/tolerance_time_plugin/publication.rb index b52b36e..24fae23 100644 --- a/plugins/tolerance_time/lib/tolerance_time_plugin/publication.rb +++ b/plugins/tolerance_time/lib/tolerance_time_plugin/publication.rb @@ -13,7 +13,7 @@ class ToleranceTimePlugin::Publication < ActiveRecord::Base def expired? profile = (target.kind_of?(Article) ? target.profile : target.article.profile) - profile_tolerance = ToleranceTimePlugin::Tolerance.find_by_profile_id(profile.id) + profile_tolerance = ToleranceTimePlugin::Tolerance.find_by profile_id: profile.id content_tolerance = profile_tolerance ? profile_tolerance.content_tolerance : nil comment_tolerance = profile_tolerance ? profile_tolerance.comment_tolerance : nil if target.kind_of?(Article) diff --git a/plugins/tolerance_time/test/unit/article_test.rb b/plugins/tolerance_time/test/unit/article_test.rb index f22ac5b..52fd5a4 100644 --- a/plugins/tolerance_time/test/unit/article_test.rb +++ b/plugins/tolerance_time/test/unit/article_test.rb @@ -3,11 +3,11 @@ require 'test_helper' class ArticleTest < ActiveSupport::TestCase should 'create a publication after publishing the article' do article = fast_create(Article, :published => false, :profile_id => fast_create(Profile).id) - assert_nil ToleranceTimePlugin::Publication.find_by_target(article) + assert_nil ToleranceTimePlugin::Publication.find_by target: article article.published = true article.save! - assert_not_nil ToleranceTimePlugin::Publication.find_by_target(article) + assert_not_nil ToleranceTimePlugin::Publication.find_by target: article end should 'destroy publication if the article is destroyed' do diff --git a/plugins/tolerance_time/test/unit/comment_test.rb b/plugins/tolerance_time/test/unit/comment_test.rb index 312af21..d8a85c3 100644 --- a/plugins/tolerance_time/test/unit/comment_test.rb +++ b/plugins/tolerance_time/test/unit/comment_test.rb @@ -7,7 +7,7 @@ class CommentTest < ActiveSupport::TestCase assert_difference 'ToleranceTimePlugin::Publication.count', 1 do comment.save! end - assert_not_nil ToleranceTimePlugin::Publication.find_by_target(comment) + assert_not_nil ToleranceTimePlugin::Publication.find_by target: comment end should 'destroy publication if the comment is destroyed' do diff --git a/plugins/tolerance_time/test/unit/tolerance_time_plugin/publication_test.rb b/plugins/tolerance_time/test/unit/tolerance_time_plugin/publication_test.rb index 2ddb4e7..4d339e2 100644 --- a/plugins/tolerance_time/test/unit/tolerance_time_plugin/publication_test.rb +++ b/plugins/tolerance_time/test/unit/tolerance_time_plugin/publication_test.rb @@ -26,7 +26,7 @@ class ToleranceTimePlugin::PublicationTest < ActiveSupport::TestCase should 'be able to find publication by target' do article = fast_create(Article) publication = ToleranceTimePlugin::Publication.create!(:target => article) - assert_equal publication, ToleranceTimePlugin::Publication.find_by_target(article) + assert_equal publication, ToleranceTimePlugin::Publication.find_by(target: article) end should 'avaliate if the publication is expired' do diff --git a/plugins/video/lib/ext/article.rb b/plugins/video/lib/ext/article.rb index 8e97c3b..abeeb6a 100644 --- a/plugins/video/lib/ext/article.rb +++ b/plugins/video/lib/ext/article.rb @@ -2,7 +2,7 @@ require_dependency 'article' class Article - scope :video_gallery, :conditions => ["articles.type = 'VideoPlugin::VideoGallery'"] + scope :video_gallery, -> { where "articles.type = 'VideoPlugin::VideoGallery'" } #FIXME This should be done via hotspot def self.folder_types_with_video @@ -16,10 +16,9 @@ class Article def self.owner_video_galleries(owner) conditions = owner.kind_of?(Environment) ? [] : ["profile_id = ?", owner.id] - result = Article.video_gallery.find( - :all, - :order => 'created_at desc', - :conditions => conditions) + result = Article.video_gallery + .order('created_at desc') + .where(conditions) end end diff --git a/plugins/work_assignment/controllers/work_assignment_plugin_myprofile_controller.rb b/plugins/work_assignment/controllers/work_assignment_plugin_myprofile_controller.rb index 6339192..dadb553 100644 --- a/plugins/work_assignment/controllers/work_assignment_plugin_myprofile_controller.rb +++ b/plugins/work_assignment/controllers/work_assignment_plugin_myprofile_controller.rb @@ -7,7 +7,7 @@ before_filter :protect_if, :only => [:edit_visibility] def edit_visibility unless params[:article_id].blank? - folder = profile.environment.articles.find_by_id(params[:article_id]) + folder = profile.environment.articles.find_by id: params[:article_id] @back_to = url_for(folder.parent.url) unless params[:article].blank? folder.published = params[:article][:published] @@ -29,7 +29,7 @@ def edit_visibility protected def protect_if - article = environment.articles.find_by_id(params[:article_id]) + article = environment.articles.find_by id: params[:article_id] render_access_denied unless (user && !article.nil? && (user.is_member_of? article.profile) && article.parent.allow_visibility_edition && article.folder? && (article.author == user || user.has_permission?('view_private_content', profile))) diff --git a/plugins/work_assignment/lib/work_assignment_plugin.rb b/plugins/work_assignment/lib/work_assignment_plugin.rb index 5f23616..fe0104e 100644 --- a/plugins/work_assignment/lib/work_assignment_plugin.rb +++ b/plugins/work_assignment/lib/work_assignment_plugin.rb @@ -38,7 +38,7 @@ class WorkAssignmentPlugin < Noosfero::Plugin def content_viewer_controller_filters block = proc do path = get_path(params[:page], params[:format]) - content = profile.articles.find_by_path(path) + content = profile.articles.find_by path: path if WorkAssignmentPlugin.is_submission?(content) && !WorkAssignmentPlugin.can_download_submission?(user, content) render_access_denied @@ -75,7 +75,7 @@ class WorkAssignmentPlugin < Noosfero::Plugin def upload_files_extra_fields(article) proc do - @article = Article.find_by_id(article) + @article = Article.find_by id: article if params[:parent_id] && !@article.nil? && @article.type == "WorkAssignmentPlugin::WorkAssignment" render :partial => 'notify_text_field', :locals => { :size => '45'} end diff --git a/plugins/work_assignment/lib/work_assignment_plugin/helper.rb b/plugins/work_assignment/lib/work_assignment_plugin/helper.rb index 7c97f54..8292b42 100644 --- a/plugins/work_assignment/lib/work_assignment_plugin/helper.rb +++ b/plugins/work_assignment/lib/work_assignment_plugin/helper.rb @@ -73,7 +73,7 @@ module WorkAssignmentPlugin::Helper end def display_privacy_button(author_folder, user) - folder = environment.articles.find_by_id(author_folder.id) + folder = environment.articles.find_by id: author_folder.id work_assignment = folder.parent @back_to = url_for(work_assignment.url) diff --git a/plugins/work_assignment/lib/work_assignment_plugin/work_assignment.rb b/plugins/work_assignment/lib/work_assignment_plugin/work_assignment.rb index a27f0a2..b5e285f 100644 --- a/plugins/work_assignment/lib/work_assignment_plugin/work_assignment.rb +++ b/plugins/work_assignment/lib/work_assignment_plugin/work_assignment.rb @@ -7,7 +7,7 @@ class WorkAssignmentPlugin::WorkAssignment < Folder attr_accessible :publish_submissions attr_accessible :default_email attr_accessible :allow_visibility_edition - + def self.icon_name(article = nil) 'work-assignment' end @@ -39,14 +39,14 @@ class WorkAssignmentPlugin::WorkAssignment < Folder end def find_or_create_author_folder(author) - children.find_by_slug(author.name.to_slug) || Folder.create!( + children.find_by(slug: author.name.to_slug) || Folder.create!( { :name => author.name, :parent => self, :profile => profile, :author => author, :published => publish_submissions, - }, + }, :without_protection => true ) end @@ -58,5 +58,5 @@ class WorkAssignmentPlugin::WorkAssignment < Folder def cache_key_with_person(params = {}, user = nil, language = 'en') cache_key_without_person + (user && profile.members.include?(user) ? "-#{user.identifier}" : '') end - alias_method_chain :cache_key, :person + alias_method_chain :cache_key, :person end diff --git a/plugins/work_assignment/test/functional/work_assignment_plugin_myprofile_controller_test.rb b/plugins/work_assignment/test/functional/work_assignment_plugin_myprofile_controller_test.rb index efce240..99cca57 100644 --- a/plugins/work_assignment/test/functional/work_assignment_plugin_myprofile_controller_test.rb +++ b/plugins/work_assignment/test/functional/work_assignment_plugin_myprofile_controller_test.rb @@ -32,7 +32,7 @@ class WorkAssignmentPluginMyprofileControllerTest < ActionController::TestCase }, :without_protection => true ) - submission = UploadedFile.find_by_filename("test.txt") + submission = UploadedFile.find_by filename: 'test.txt' assert_equal false, submission.published assert_equal false, submission.parent.published @@ -78,7 +78,7 @@ class WorkAssignmentPluginMyprofileControllerTest < ActionController::TestCase :without_protection => true ) logout - submission = UploadedFile.find_by_filename("test.txt") + submission = UploadedFile.find_by filename: 'test.txt' assert_equal false, submission.parent.published assert_equal false, submission.published @@ -113,7 +113,7 @@ class WorkAssignmentPluginMyprofileControllerTest < ActionController::TestCase login_as :other_user @organization.add_member(other_person) - submission = UploadedFile.find_by_filename("test.txt") + submission = UploadedFile.find_by filename: 'test.txt' assert_equal(submission.author, @person) post :edit_visibility, :profile => @organization.identifier, :article_id => parent.id @@ -143,7 +143,7 @@ class WorkAssignmentPluginMyprofileControllerTest < ActionController::TestCase }, :without_protection => true ) - submission = UploadedFile.find_by_filename("test.txt") + submission = UploadedFile.find_by filename: 'test.txt' assert_equal false, submission.article_privacy_exceptions.include?(other_person) post :edit_visibility, :profile => @organization.identifier, :article_id => parent.id, :article => { :published => false }, :q => other_person.id submission.reload @@ -166,7 +166,7 @@ class WorkAssignmentPluginMyprofileControllerTest < ActionController::TestCase :without_protection => true ) @organization.remove_member(@person) - submission = UploadedFile.find_by_filename("test.txt") + submission = UploadedFile.find_by filename: 'test.txt' assert_equal false, (@person.is_member_of? submission.profile) diff --git a/plugins/work_assignment/test/unit/work_assingment_plugin/work_assignment_test.rb b/plugins/work_assignment/test/unit/work_assingment_plugin/work_assignment_test.rb index b2bc27d..3bb5814 100644 --- a/plugins/work_assignment/test/unit/work_assingment_plugin/work_assignment_test.rb +++ b/plugins/work_assignment/test/unit/work_assingment_plugin/work_assignment_test.rb @@ -5,10 +5,10 @@ class WorkAssignmentTest < ActiveSupport::TestCase profile = fast_create(Profile) author = fast_create(Person) work_assignment = WorkAssignmentPlugin::WorkAssignment.create!(:name => 'Sample Work Assignment', :profile => profile) - assert_nil work_assignment.children.find_by_slug(author.identifier) + assert_nil work_assignment.children.find_by slug: author.identifier folder = work_assignment.find_or_create_author_folder(author) - assert_not_nil work_assignment.children.find_by_slug(author.identifier) + assert_not_nil work_assignment.children.find_by slug: author.identifier assert_equal folder, work_assignment.find_or_create_author_folder(author) end diff --git a/plugins/work_assignment/views/work_assignment_plugin_myprofile/edit_visibility.html.erb b/plugins/work_assignment/views/work_assignment_plugin_myprofile/edit_visibility.html.erb index 3690f78..9986aff 100644 --- a/plugins/work_assignment/views/work_assignment_plugin_myprofile/edit_visibility.html.erb +++ b/plugins/work_assignment/views/work_assignment_plugin_myprofile/edit_visibility.html.erb @@ -2,7 +2,7 @@ <%= labelled_form_for 'article', :html => { :multipart => true, :class => @type } do |f| %> - <% @article = environment.articles.find_by_id((params[:article_id]))%> + <% @article = environment.articles.find_by id: params[:article_id] %> <% @tokenized_children = params[:tokenized_children]%> diff --git a/script/apply-template b/script/apply-template index d48bad5..e2713b2 100755 --- a/script/apply-template +++ b/script/apply-template @@ -65,7 +65,7 @@ when 'community' when 'person' template = env.person_template offset = 0 - while person = Person.find(:first, :order => :id, :offset => offset) + while person = Person.order(:id).offset(offset).first if person != template report_doing offset, person.identifier person.apply_template(template) diff --git a/test/api/helpers_test.rb b/test/api/helpers_test.rb index 5c0e4d0..9a877db 100644 --- a/test/api/helpers_test.rb +++ b/test/api/helpers_test.rb @@ -45,7 +45,7 @@ class APIHelpersTest < ActiveSupport::TestCase # should 'set current_user to nil after logout' do # user = create_user('someuser') # user.stubs(:private_token_expired?).returns(false) -# User.stubs(:find_by_private_token).returns(user) +# User.stubs(:find_by(private_token).returns: user) # assert_not_nil current_user # assert false # logout @@ -103,7 +103,8 @@ class APIHelpersTest < ActiveSupport::TestCase fast_create(Article, :profile_id => user.person.id) user.generate_private_token! - User.expects(:find_by_private_token).returns(user) + self.params = {private_token: user.private_token} + User.expects(:find_by).with(private_token: user.private_token).returns(user) assert_equal a, find_article(user.person.articles, a.id) end @@ -114,7 +115,8 @@ class APIHelpersTest < ActiveSupport::TestCase fast_create(Article, :profile_id => p.id) user.generate_private_token! - User.expects(:find_by_private_token).returns(user) + self.params = {private_token: user.private_token} + User.expects(:find_by).with(private_token: user.private_token).returns(user) assert_equal 403, find_article(p.articles, a.id).last end diff --git a/test/functional/account_controller_test.rb b/test/functional/account_controller_test.rb index ecfb90a..12156a9 100644 --- a/test/functional/account_controller_test.rb +++ b/test/functional/account_controller_test.rb @@ -198,7 +198,7 @@ class AccountControllerTest < ActionController::TestCase post :change_password, :current_password => 'wrong', :new_password => 'blabla', :new_password_confirmation => 'blabla' assert_response :success assert_template 'change_password' - refute User.find_by_login('ze').authenticated?('blabla') + refute User.find_by(login: 'ze').authenticated?('blabla') assert_equal users(:ze), @controller.send(:current_user) end @@ -454,7 +454,7 @@ class AccountControllerTest < ActionController::TestCase ent.reload - assert_nil User.find_by_login('test_user') + assert_nil User.find_by(login: 'test_user') assert ent.blocked? assert_template 'blocked' end @@ -637,7 +637,7 @@ class AccountControllerTest < ActionController::TestCase env.enable('skip_new_user_email_confirmation') env.save! new_user(:login => 'activated_user') - user = User.find_by_login('activated_user') + user = User.find_by(login: 'activated_user') assert user.activated? end @@ -702,14 +702,14 @@ class AccountControllerTest < ActionController::TestCase end Noosfero::Plugin.stubs(:all).returns([Plugin1.name, Plugin2.name]) - e = User.find_by_login('ze').environment + e = User.find_by(login: 'ze').environment e.enable_plugin(Plugin1.name) e.enable_plugin(Plugin2.name) login_as 'ze' xhr :get, :user_data - assert_equal User.find_by_login('ze').data_hash(@controller.gravatar_default).merge({ 'foo' => 'bar', 'test' => 5 }), ActiveSupport::JSON.decode(@response.body) + assert_equal User.find_by(login: 'ze').data_hash(@controller.gravatar_default).merge({ 'foo' => 'bar', 'test' => 5 }), ActiveSupport::JSON.decode(@response.body) end should 'activate user when activation code is present and correct' do diff --git a/test/functional/categories_controller_test.rb b/test/functional/categories_controller_test.rb index 2687550..b96b4cb 100644 --- a/test/functional/categories_controller_test.rb +++ b/test/functional/categories_controller_test.rb @@ -152,7 +152,7 @@ class CategoriesControllerTest < ActionController::TestCase should 'use parent\'s type to determine subcategory\'s type' do parent = create(ProductCategory, :name => 'Sample category', :environment => Environment.default) post :new, :parent_id => parent.id, :parent_type => parent.class.name, :category => {:name => 'Subcategory'} - sub = ProductCategory.find_by_name('Subcategory') + sub = ProductCategory.find_by(name: 'Subcategory') assert_equal parent.class, sub.class end diff --git a/test/functional/cms_controller_test.rb b/test/functional/cms_controller_test.rb index fd99796..9160c72 100644 --- a/test/functional/cms_controller_test.rb +++ b/test/functional/cms_controller_test.rb @@ -200,7 +200,7 @@ class CmsControllerTest < ActionController::TestCase post :new, :type => 'TinyMceArticle', :profile => profile.identifier, :article => { :name => 'changed by me', :body => 'content ...' } - a = profile.articles.find_by_path('changed-by-me') + a = profile.articles.find_by(path: 'changed-by-me') assert_not_nil a assert_equal profile, a.last_changed_by end @@ -308,14 +308,14 @@ class CmsControllerTest < ActionController::TestCase assert_difference 'UploadedFile.count' do post :new, :type => UploadedFile.name, :profile => profile.identifier, :article => { :uploaded_data => fixture_file_upload('/files/test.txt', 'text/plain')} end - assert_not_nil profile.articles.find_by_path('test.txt') + assert_not_nil profile.articles.find_by(path: 'test.txt') assigns(:article).destroy end should 'be able to update an uploaded file' do post :new, :type => UploadedFile.name, :profile => profile.identifier, :article => { :uploaded_data => fixture_file_upload('/files/test.txt', 'text/plain')} - file = profile.articles.find_by_path('test.txt') + file = profile.articles.find_by(path: 'test.txt') assert_equal 'test.txt', file.name post :edit, :profile => profile.identifier, :id => file.id, :article => { :uploaded_data => fixture_file_upload('/files/test_another.txt', 'text/plain')} @@ -347,8 +347,8 @@ class CmsControllerTest < ActionController::TestCase assert_difference 'UploadedFile.count', 2 do post :upload_files, :profile => profile.identifier, :uploaded_files => [fixture_file_upload('/files/test.txt', 'text/plain'), fixture_file_upload('/files/rails.png', 'text/plain')] end - assert_not_nil profile.articles.find_by_path('test.txt') - assert_not_nil profile.articles.find_by_path('rails.png') + assert_not_nil profile.articles.find_by(path: 'test.txt') + assert_not_nil profile.articles.find_by(path: 'rails.png') end should 'upload to rigth folder' do @@ -364,7 +364,7 @@ class CmsControllerTest < ActionController::TestCase f = Folder.new(:name => 'f'); profile.articles << f; f.save! post :upload_files, :profile => profile.identifier, :parent_id => f.id, :uploaded_files => [fixture_file_upload('/files/test.txt', 'text/plain')] - uf = profile.articles.find_by_name('test.txt') + uf = profile.articles.find_by(name: 'test.txt') assert_equal profile, uf.author end @@ -385,14 +385,14 @@ class CmsControllerTest < ActionController::TestCase assert_nothing_raised do post :upload_files, :profile => profile.identifier, :uploaded_files => [fixture_file_upload('/files/test.txt', 'text/plain'), '' ] end - assert_not_nil profile.articles.find_by_path('test.txt') + assert_not_nil profile.articles.find_by(path: 'test.txt') end should 'not crash when parent_id is blank' do assert_nothing_raised do post :upload_files, :profile => profile.identifier, :parent_id => '', :uploaded_files => [fixture_file_upload('/files/test.txt', 'text/plain'), '' ] end - assert_not_nil profile.articles.find_by_path('test.txt') + assert_not_nil profile.articles.find_by(path: 'test.txt') end should 'redirect to cms after uploading files' do @@ -512,7 +512,7 @@ class CmsControllerTest < ActionController::TestCase # post is in c1 and c3 post :new, :type => TextileArticle.name, :profile => profile.identifier, :article => { :name => 'adding-categories-test', :category_ids => [ c1.id, c3.id] } - saved = profile.articles.find_by_name('adding-categories-test') + saved = profile.articles.find_by(name: 'adding-categories-test') assert_includes saved.categories, c1 assert_not_includes saved.categories, c2 assert_includes saved.categories, c3 @@ -527,7 +527,7 @@ class CmsControllerTest < ActionController::TestCase # post is in c1, c3 and c3 post :new, :type => TextileArticle.name, :profile => profile.identifier, :article => { :name => 'adding-categories-test', :category_ids => [ c1.id, c3.id, c3.id ] } - saved = profile.articles.find_by_name('adding-categories-test') + saved = profile.articles.find_by(name: 'adding-categories-test') assert_equal [c1, c3], saved.categories.all end @@ -559,7 +559,7 @@ class CmsControllerTest < ActionController::TestCase should 'keep informed parent_id' do fast_create(:blog, :name=>"Sample blog", :profile_id=>@profile.id) - profile.home_page = profile.blogs.find_by_name "Sample blog" + profile.home_page = profile.blogs.find_by name: "Sample blog" profile.save! get :new, :profile => @profile.identifier, :parent_id => profile.home_page.id, :type => 'TextileArticle' @@ -608,20 +608,20 @@ class CmsControllerTest < ActionController::TestCase should 'redirect to article after creating top-level article' do post :new, :profile => profile.identifier, :type => 'TextileArticle', :article => { :name => 'top-level-article' } - assert_redirected_to @profile.articles.find_by_name('top-level-article').url + assert_redirected_to @profile.articles.find_by(name: 'top-level-article').url end should 'redirect to article after creating article inside a folder' do f = Folder.new(:name => 'f'); profile.articles << f; f.save! post :new, :profile => profile.identifier, :type => 'TextileArticle', :parent_id => f.id, :article => { :name => 'article-inside-folder' } - assert_redirected_to @profile.articles.find_by_name('article-inside-folder').url + assert_redirected_to @profile.articles.find_by(name: 'article-inside-folder').url end should 'redirect back to article after editing top-level article' do f = Folder.new(:name => 'top-level-article'); profile.articles << f; f.save! post :edit, :profile => profile.identifier, :id => f.id - assert_redirected_to @profile.articles.find_by_name('top-level-article').url + assert_redirected_to @profile.articles.find_by(name: 'top-level-article').url end should 'redirect back to article after editing article inside a folder' do @@ -629,7 +629,7 @@ class CmsControllerTest < ActionController::TestCase a = create(TextileArticle, :parent => f, :name => 'article-inside-folder', :profile_id => profile.id) post :edit, :profile => profile.identifier, :id => a.id - assert_redirected_to @profile.articles.find_by_name('article-inside-folder').url + assert_redirected_to @profile.articles.find_by(name: 'article-inside-folder').url end should 'point back to index when cancelling creation of top-level article' do @@ -696,14 +696,14 @@ class CmsControllerTest < ActionController::TestCase should 'be able to add image with alignment' do post :new, :type => 'TinyMceArticle', :profile => profile.identifier, :article => { :name => 'image-alignment', :body => "the text of the article with image right align..." } - saved = TinyMceArticle.find_by_name('image-alignment') + saved = TinyMceArticle.find_by(name: 'image-alignment') assert_match //, saved.body assert_match //, saved.body end should 'be able to add image with alignment when textile' do post :new, :type => 'TextileArticle', :profile => profile.identifier, :article => { :name => 'image-alignment', :body => "the text of the article with image right align..." } - saved = TextileArticle.find_by_name('image-alignment') + saved = TextileArticle.find_by(name: 'image-alignment') assert_match /align="right"/, saved.body end @@ -770,7 +770,7 @@ class CmsControllerTest < ActionController::TestCase should 'go to public view after creating article coming from there' do post :new, :profile => 'testinguser', :type => 'TextileArticle', :back_to => 'public_view', :article => { :name => 'new-article-from-public-view' } assert_response :redirect - assert_redirected_to @profile.articles.find_by_name('new-article-from-public-view').url + assert_redirected_to @profile.articles.find_by(name: 'new-article-from-public-view').url end should 'keep the back_to hint in unsuccessfull saves' do @@ -1034,14 +1034,14 @@ class CmsControllerTest < ActionController::TestCase assert_difference 'Blog.count' do post :new, :type => Blog.name, :profile => profile.identifier, :article => { :name => 'my-blog' }, :back_to => 'control_panel' end - assert_redirected_to @profile.articles.find_by_name('my-blog').view_url + assert_redirected_to @profile.articles.find_by(name: 'my-blog').view_url end should 'back to blog after config blog' do profile.articles << Blog.new(:name => 'my-blog', :profile => profile) post :edit, :profile => profile.identifier, :id => profile.blog.id - assert_redirected_to @profile.articles.find_by_name('my-blog').view_url + assert_redirected_to @profile.articles.find_by(name: 'my-blog').view_url end should 'back to control panel if cancel create blog' do @@ -1068,7 +1068,7 @@ class CmsControllerTest < ActionController::TestCase :article => {:uploaded_data => fixture_file_upload('/files/rails.png', 'image/png')} process_delayed_job_queue - file = FilePresenter.for profile.articles.find_by_name('rails.png') + file = FilePresenter.for profile.articles.find_by(name: 'rails.png') assert File.exists?(file.icon_name) file.destroy end @@ -1079,7 +1079,7 @@ class CmsControllerTest < ActionController::TestCase :article => {:uploaded_data => fixture_file_upload('/files/rails.png', 'image/png')} process_delayed_job_queue - file = FilePresenter.for profile.articles.find_by_name('rails.png') + file = FilePresenter.for profile.articles.find_by(name: 'rails.png') assert File.exists?(file.icon_name) file.destroy end @@ -1320,8 +1320,8 @@ class CmsControllerTest < ActionController::TestCase should 'create thumbnails for images with delayed_job' do post :upload_files, :profile => profile.identifier, :uploaded_files => [fixture_file_upload('/files/rails.png', 'image/png'), fixture_file_upload('/files/test.txt', 'text/plain')] - file_1 = profile.articles.find_by_path('rails.png') - file_2 = profile.articles.find_by_path('test.txt') + file_1 = profile.articles.find_by(path: 'rails.png') + file_2 = profile.articles.find_by(path: 'test.txt') process_delayed_job_queue @@ -1413,7 +1413,7 @@ class CmsControllerTest < ActionController::TestCase assert_difference 'Forum.count' do post :new, :type => Forum.name, :profile => profile.identifier, :article => { :name => 'my-forum' }, :back_to => 'control_panel' end - assert_redirected_to @profile.articles.find_by_name('my-forum').view_url + assert_redirected_to @profile.articles.find_by(name: 'my-forum').view_url end should 'back to forum after config forum' do @@ -1421,7 +1421,7 @@ class CmsControllerTest < ActionController::TestCase post :new, :type => Forum.name, :profile => profile.identifier, :article => { :name => 'my-forum' }, :back_to => 'control_panel' end post :edit, :type => Forum.name, :profile => profile.identifier, :article => { :name => 'my forum' }, :id => profile.forum.id - assert_redirected_to @profile.articles.find_by_name('my forum').view_url + assert_redirected_to @profile.articles.find_by(name: 'my forum').view_url end should 'back to control panel if cancel create forum' do @@ -1829,7 +1829,7 @@ class CmsControllerTest < ActionController::TestCase post :new, :type => 'TinyMceArticle', :profile => profile.identifier, :article => { :name => 'Sample Article', :body => 'content ...' } - a = profile.articles.find_by_path('sample-article') + a = profile.articles.find_by(path: 'sample-article') assert_not_nil a assert_equal profile, a.author end @@ -1913,7 +1913,7 @@ class CmsControllerTest < ActionController::TestCase post :new, :type => 'TinyMceArticle', :profile => profile.identifier, :article => { :name => 'changed by me', :body => 'content ...' } - a = profile.articles.find_by_path('changed-by-me') + a = profile.articles.find_by(path: 'changed-by-me') assert_not_nil a assert_equal profile, a.created_by end @@ -1960,13 +1960,13 @@ class CmsControllerTest < ActionController::TestCase post :new, :type => 'TinyMceArticle', :profile => profile.identifier, :parent_id => f.id, :article => { :name => 'Main Article', :body => 'some content' } - main_article = profile.articles.find_by_name('Main Article') + main_article = profile.articles.find_by(name: 'Main Article') assert_not_nil main_article post :new, :type => 'TinyMceArticle', :profile => profile.identifier, :parent_id => f.id, :id => main_article.id, :clone => true - cloned_main_article = profile.articles.find_by_name('Main Article') + cloned_main_article = profile.articles.find_by(name: 'Main Article') assert_not_nil cloned_main_article assert_equal main_article.parent_id, cloned_main_article.parent_id diff --git a/test/functional/content_viewer_controller_test.rb b/test/functional/content_viewer_controller_test.rb index d84c860..9b85802 100644 --- a/test/functional/content_viewer_controller_test.rb +++ b/test/functional/content_viewer_controller_test.rb @@ -1444,7 +1444,7 @@ class ContentViewerControllerTest < ActionController::TestCase community.add_member(@profile) community.save! - blog = community.articles.find_by_name("Blog") + blog = community.articles.find_by(name: "Blog") article = TinyMceArticle.create(:name => 'Article to be shared with images', :body => 'This article should be shared with all social networks', @@ -1570,7 +1570,7 @@ class ContentViewerControllerTest < ActionController::TestCase community.add_member(@profile) community.save! - blog = community.articles.find_by_name("Blog") + blog = community.articles.find_by(name: "Blog") blog.visualization_format = 'compact' blog.save! diff --git a/test/functional/environment_themes_controller_test.rb b/test/functional/environment_themes_controller_test.rb index e8c7512..9ef4720 100644 --- a/test/functional/environment_themes_controller_test.rb +++ b/test/functional/environment_themes_controller_test.rb @@ -12,7 +12,7 @@ class EnvironmentThemesControllerTest < ActionController::TestCase @env = Environment.default login = create_admin_user(@env) login_as(login) - @profile = User.find_by_login(login).person + @profile = User.find_by(login: login).person end def teardown diff --git a/test/functional/features_controller_test.rb b/test/functional/features_controller_test.rb index 99fab9f..647d79f 100644 --- a/test/functional/features_controller_test.rb +++ b/test/functional/features_controller_test.rb @@ -162,7 +162,7 @@ class FeaturesControllerTest < ActionController::TestCase should 'create custom field' do uses_host 'anhetegua.net' - assert_nil Environment.find(2).custom_fields.find_by_name('foo') + assert_nil Environment.find(2).custom_fields.find_by(name: 'foo') post :manage_custom_fields, :customized_type => 'Person', :custom_fields => { Time.now.to_i => { :name => 'foo', @@ -175,7 +175,7 @@ class FeaturesControllerTest < ActionController::TestCase } } assert_redirected_to :action => 'manage_fields' - assert_not_nil Environment.find(2).custom_fields.find_by_name('foo') + assert_not_nil Environment.find(2).custom_fields.find_by(name: 'foo') end should 'update custom field' do @@ -204,7 +204,7 @@ class FeaturesControllerTest < ActionController::TestCase post :manage_custom_fields, :customized_type => 'Enterprise' assert_redirected_to :action => 'manage_fields' - assert_nil Environment.find(2).custom_fields.find_by_name('foo') + assert_nil Environment.find(2).custom_fields.find_by(name: 'foo') end end diff --git a/test/functional/manage_products_controller_test.rb b/test/functional/manage_products_controller_test.rb index a7347f4..78a6ab1 100644 --- a/test/functional/manage_products_controller_test.rb +++ b/test/functional/manage_products_controller_test.rb @@ -84,7 +84,7 @@ class ManageProductsControllerTest < ActionController::TestCase assert_response :success assert assigns(:product) refute assigns(:product).new_record? - assert_equal product, Product.find_by_name('new test product') + assert_equal product, Product.find_by(name: 'new test product') end should "edit product description" do @@ -93,7 +93,7 @@ class ManageProductsControllerTest < ActionController::TestCase assert_response :success assert assigns(:product) refute assigns(:product).new_record? - assert_equal 'A very good product!', Product.find_by_name('test product').description + assert_equal 'A very good product!', Product.find_by(name: 'test product').description end should "edit product image" do @@ -102,7 +102,7 @@ class ManageProductsControllerTest < ActionController::TestCase assert_response :success assert assigns(:product) refute assigns(:product).new_record? - assert_equal 'rails.png', Product.find_by_name('test product').image.filename + assert_equal 'rails.png', Product.find_by(name: 'test product').image.filename end should "not edit to invalid parameters" do @@ -126,7 +126,7 @@ class ManageProductsControllerTest < ActionController::TestCase assert_response :redirect assert_redirected_to :action => 'index' assert assigns(:product) - refute Product.find_by_name('test product') + refute Product.find_by(name: 'test product') end end @@ -138,7 +138,7 @@ class ManageProductsControllerTest < ActionController::TestCase assert_response :redirect assert_redirected_to :controller => "manage_products", :profile => @enterprise.identifier, :action => 'show', :id => product.id assert assigns(:product) - assert Product.find_by_name('test product') + assert Product.find_by(name: 'test product') end end diff --git a/test/functional/memberships_controller_test.rb b/test/functional/memberships_controller_test.rb index 10b7352..1fddf6b 100644 --- a/test/functional/memberships_controller_test.rb +++ b/test/functional/memberships_controller_test.rb @@ -32,7 +32,7 @@ class MembershipsControllerTest < ActionController::TestCase post :new_community, :profile => profile.identifier, :community => { :name => 'My shiny new community', :description => 'This is a community devoted to anything interesting we find in the internet '} assert_response :redirect - assert Community.find_by_identifier('my-shiny-new-community').members.include?(profile), "Creator user should be added as member of the community just created" + assert Community.find_by(identifier: 'my-shiny-new-community').members.include?(profile), "Creator user should be added as member of the community just created" end end @@ -42,7 +42,7 @@ class MembershipsControllerTest < ActionController::TestCase CustomField.create!(:name => "zombies", :format=>"String", :default_value => "awrrr", :customized_type=>"Community", :active => true, :required => true, :signup => true, :environment => Environment.default) post :new_community, :profile => profile.identifier, :community => { :name => 'My shiny new community', :description => 'This is a community devoted to anything interesting we find in the internet '}, "profile_data"=>{"custom_values"=>{"zombies"=>{"value"=>"BRAINSSS"}}} assert_response :redirect - assert Community.find_by_identifier('my-shiny-new-community').members.include?(profile), "Creator user should be added as member of the community just created" + assert Community.find_by(identifier: 'my-shiny-new-community').members.include?(profile), "Creator user should be added as member of the community just created" end end end @@ -94,7 +94,7 @@ class MembershipsControllerTest < ActionController::TestCase should 'current user is added as admin after create new community' do post :new_community, :profile => profile.identifier, :community => { :name => 'My shiny new community', :description => 'This is a community devoted to anything interesting we find in the internet '} - assert_equal Profile::Roles.admin(profile.environment.id), profile.find_roles(Community.find_by_identifier('my-shiny-new-community')).first.role + assert_equal Profile::Roles.admin(profile.environment.id), profile.find_roles(Community.find_by(identifier: 'my-shiny-new-community')).first.role end should 'display button to create community' do diff --git a/test/functional/profile_design_controller_test.rb b/test/functional/profile_design_controller_test.rb index 6c4a527..1015844 100644 --- a/test/functional/profile_design_controller_test.rb +++ b/test/functional/profile_design_controller_test.rb @@ -30,37 +30,29 @@ class ProfileDesignControllerTest < ActionController::TestCase ###### BOX 1 @b1 = ArticleBlock.new @box1.blocks << @b1 - @b1.save! @b2 = Block.new @box1.blocks << @b2 - @b2.save! ###### BOX 2 @b3 = Block.new @box2.blocks << @b3 - @b3.save! @b4 = MainBlock.new @box2.blocks << @b4 - @b4.save! @b5 = Block.new @box2.blocks << @b5 - @b5.save! @b6 = Block.new @box2.blocks << @b6 - @b6.save! ###### BOX 3 @b7 = Block.new @box3.blocks << @b7 - @b7.save! @b8 = Block.new @box3.blocks << @b8 - @b8.save! @request.env['HTTP_REFERER'] = '/editor' @@ -424,7 +416,7 @@ class ProfileDesignControllerTest < ActionController::TestCase should 'be able to save FeedReaderBlock configurations' do @box1.blocks << FeedReaderBlock.new(:address => 'feed address') holder.blocks(true) - block = @box1.blocks.last + block = @box1.blocks.find_by(type: FeedReaderBlock) post :save, :profile => 'designtestuser', :id => block.id, :block => {:address => 'new feed address', :limit => '20'} diff --git a/test/functional/profile_members_controller_test.rb b/test/functional/profile_members_controller_test.rb index 3332325..67d5158 100644 --- a/test/functional/profile_members_controller_test.rb +++ b/test/functional/profile_members_controller_test.rb @@ -250,7 +250,7 @@ class ProfileMembersControllerTest < ActionController::TestCase u = create_user('member_wannabe').person post :add_member, :profile => ent.identifier, :id => u.id - assert_equivalent Profile::Roles.all_roles(ent.environment).compact, u.role_assignments.find_all_by_resource_id(ent.id).map(&:role).compact + assert_equivalent Profile::Roles.all_roles(ent.environment).compact, u.role_assignments.where(resource_id: ent.id).map(&:role).compact end should 'not add member to community' do diff --git a/test/functional/profile_roles_controller_test.rb b/test/functional/profile_roles_controller_test.rb index deb6370..bb007e4 100644 --- a/test/functional/profile_roles_controller_test.rb +++ b/test/functional/profile_roles_controller_test.rb @@ -7,7 +7,7 @@ class ProfileRolesControllerTest < ActionController::TestCase @controller = ProfileRolesController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new - @role = Role.find(:first) + @role = Role.first end should 'create a custom role' do @@ -55,7 +55,7 @@ class ProfileRolesControllerTest < ActionController::TestCase login_as :admin_user role = Role.create!({:name => 'delete_article', :key => 'profile_delete_article', :profile_id => community.id, :environment => Environment.default}, :without_protection => true) admin.add_role(role, community) - moderator_role = Role.find_by_name("moderator") + moderator_role = Role.find_by(name: "moderator") assert_not_includes community.members_by_role(moderator_role), admin @@ -87,7 +87,7 @@ class ProfileRolesControllerTest < ActionController::TestCase moderator = create_user_with_permission('profile_admin', 'edit_profile', community) login_as :admin_user role = Role.create!({:name => 'delete_article', :key => 'profile_delete_article', :profile_id => community.id, :environment => Environment.default}, :without_protection => true) - moderator_role = Role.find_by_name("moderator") + moderator_role = Role.find_by(name: "moderator") admin.add_role(moderator_role, community) assert_not_includes community.members_by_role(role), admin diff --git a/test/functional/role_controller_test.rb b/test/functional/role_controller_test.rb index b7271cf..0c77394 100644 --- a/test/functional/role_controller_test.rb +++ b/test/functional/role_controller_test.rb @@ -8,7 +8,7 @@ class RoleControllerTest < ActionController::TestCase @controller = RoleController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new - @role = Role.find(:first) + @role = Role.first login_as(:ze) end diff --git a/test/functional/tasks_controller_test.rb b/test/functional/tasks_controller_test.rb index a3033ad..8137ce6 100644 --- a/test/functional/tasks_controller_test.rb +++ b/test/functional/tasks_controller_test.rb @@ -208,7 +208,7 @@ class TasksControllerTest < ActionController::TestCase t = ApproveArticle.create!(:name => 'test name', :article => article, :target => c, :requestor => profile) post :close, :tasks => {t.id => {:decision => 'finish', :task => {:name => 'new_name'}}} - assert_equal article, c.articles.find_by_name('new_name').reference_article + assert_equal article, c.articles.find_by(name: 'new_name').reference_article end should 'create published article in folder after finish approve article task' do @@ -221,7 +221,7 @@ class TasksControllerTest < ActionController::TestCase t = ApproveArticle.create!(:name => 'test name', :article => article, :target => c, :requestor => profile) post :close, :tasks => {t.id => {:decision => 'finish', :task => {:name => 'new_name', :article_parent_id => folder.id}}} - assert_equal folder, c.articles.find_by_name('new_name').parent + assert_equal folder, c.articles.find_by(name: 'new_name').parent end should 'be highlighted if asked when approving a published article' do @@ -234,7 +234,7 @@ class TasksControllerTest < ActionController::TestCase t = ApproveArticle.create!(:article => article, :target => c, :requestor => profile) post :close, :tasks => {t.id => {:decision => 'finish', :task => {:name => 'new_name', :article_parent_id => folder.id, :highlighted => true}}} - assert_equal true, c.articles.find_by_name('new_name').highlighted + assert_equal true, c.articles.find_by(name: 'new_name').highlighted end should 'create article of same class after choosing root folder on approve article task' do @@ -246,7 +246,7 @@ class TasksControllerTest < ActionController::TestCase t = ApproveArticle.create!(:article => article, :target => c, :requestor => profile) post :close, :tasks => {t.id => {:decision => 'finish', :task => {:name => 'new_name', :article_parent_id => ""}}} - assert_not_nil c.articles.find_by_name('new_name') + assert_not_nil c.articles.find_by(name: 'new_name') end should 'handle blank names for published articles' do @@ -266,7 +266,7 @@ class TasksControllerTest < ActionController::TestCase assert_difference 'article.class.count' do post :close, :tasks => {a.id => {:decision => 'finish', :task => {:name => "", :highlighted => "0", :article_parent_id => c_blog2.id.to_s}}} end - assert p_article = article.class.find_by_reference_article_id(article.id) + assert p_article = article.class.find_by(reference_article_id: article.id) assert_includes c_blog2.children(true), p_article end @@ -306,7 +306,7 @@ class TasksControllerTest < ActionController::TestCase t = SuggestArticle.create!(:article => {:name => 'test name', :body => 'test body'}, :name => 'some name', :email => 'test@localhost.com', :target => c) post :close, :tasks => {t.id => { :task => {}, :decision => "finish"}} - assert_not_nil TinyMceArticle.find(:first) + assert_not_nil TinyMceArticle.first end should "change the article's attributes on suggested article task approval" do @@ -322,11 +322,11 @@ class TasksControllerTest < ActionController::TestCase t.save! post :close, :tasks => {t.id => { :task => {:article => {:name => 'new article name', :body => 'new body', :source => 'http://www.noosfero.com', :source_name => 'new source'}, :name => 'new name'}, :decision => "finish"}} - assert_equal 'new article name', TinyMceArticle.find(:first).name - assert_equal 'new name', TinyMceArticle.find(:first).author_name - assert_equal 'new body', TinyMceArticle.find(:first).body - assert_equal 'http://www.noosfero.com', TinyMceArticle.find(:first).source - assert_equal 'new source', TinyMceArticle.find(:first).source_name + assert_equal 'new article name', TinyMceArticle.first.name + assert_equal 'new name', TinyMceArticle.first.author_name + assert_equal 'new body', TinyMceArticle.first.body + assert_equal 'http://www.noosfero.com', TinyMceArticle.first.source + assert_equal 'new source', TinyMceArticle.first.source_name end should "display name from article suggestion when requestor was not setted" do diff --git a/test/functional/trusted_sites_controller_test.rb b/test/functional/trusted_sites_controller_test.rb index 5a6a735..3ff191e 100644 --- a/test/functional/trusted_sites_controller_test.rb +++ b/test/functional/trusted_sites_controller_test.rb @@ -8,7 +8,7 @@ class TrustedSitesControllerTest < ActionController::TestCase @controller = TrustedSitesController.new @request = ActionController::TestRequest.new @response = ActionController::TestResponse.new - @role = Role.find(:first) + @role = Role.first @environment = Environment.default @environment.trusted_sites_for_iframe = ['existing.site.com'] @environment.save! diff --git a/test/integration/enterprise_registration_test.rb b/test/integration/enterprise_registration_test.rb index 4b15f39..874246b 100644 --- a/test/integration/enterprise_registration_test.rb +++ b/test/integration/enterprise_registration_test.rb @@ -44,7 +44,7 @@ class EnterpriseRegistrationTest < ActionDispatch::IntegrationTest assert_template 'confirmation' assert_tag :tag => 'a', :attributes => { :href => '/' } - code = CreateEnterprise.find(:first, :order => 'id desc').code + code = CreateEnterprise.order('id DESC').first.code post '/account/logout' diff --git a/test/integration/forgot_password_test.rb b/test/integration/forgot_password_test.rb index fc714e6..564216c 100644 --- a/test/integration/forgot_password_test.rb +++ b/test/integration/forgot_password_test.rb @@ -25,7 +25,7 @@ class ForgotPasswordTest < ActionDispatch::IntegrationTest assert_template 'password_recovery_sent' assert_equal 1, ChangePassword.count - code = ChangePassword.find(:first).code + code = ChangePassword.first.code get "/account/new_password/#{code}" assert_response :success @@ -58,7 +58,7 @@ class ForgotPasswordTest < ActionDispatch::IntegrationTest assert_template 'password_recovery_sent' assert_equal 1, ChangePassword.count - code = ChangePassword.find(:first).code + code = ChangePassword.first.code get "/account/new_password/#{code}" assert_response :success diff --git a/test/integration/manage_documents_test.rb b/test/integration/manage_documents_test.rb index 7afa33f..33a8150 100644 --- a/test/integration/manage_documents_test.rb +++ b/test/integration/manage_documents_test.rb @@ -28,7 +28,7 @@ class ManageDocumentsTest < ActionDispatch::IntegrationTest end assert_response :success - a = Article.find_by_path('my-article') + a = Article.find_by(path: 'my-article') assert_equal "/myuser/#{a.slug}", path end @@ -61,7 +61,7 @@ class ManageDocumentsTest < ActionDispatch::IntegrationTest assert_equal 'this is the body of the article', article.body assert_response :success - a = Article.find_by_path('my-article') + a = Article.find_by path: 'my-article' assert_equal "/myuser/#{a.slug}", path end diff --git a/test/integration/user_registers_at_the_application_test.rb b/test/integration/user_registers_at_the_application_test.rb index eb308ec..3e55467 100644 --- a/test/integration/user_registers_at_the_application_test.rb +++ b/test/integration/user_registers_at_the_application_test.rb @@ -23,7 +23,7 @@ class UserRegistersAtTheApplicationTest < ActionDispatch::IntegrationTest env.min_signup_delay = 0 env.save! - assert User.find_by_login('ze') # just to make sure that 'ze' already exists + assert User.find_by(login: 'ze') # just to make sure that 'ze' already exists get '/' assert_can_login diff --git a/test/support/authenticated_test_helper.rb b/test/support/authenticated_test_helper.rb index 37ebad4..c79e708 100644 --- a/test/support/authenticated_test_helper.rb +++ b/test/support/authenticated_test_helper.rb @@ -2,7 +2,7 @@ module AuthenticatedTestHelper # Sets the current user in the session from the user fixtures. def login_as(user) - @request.session[:user] = User.find_by_login(user.to_s).id + @request.session[:user] = User.find_by(login: user.to_s).id end def logout diff --git a/test/support/factories.rb b/test/support/factories.rb index 2970f1d..a807048 100644 --- a/test/support/factories.rb +++ b/test/support/factories.rb @@ -13,7 +13,7 @@ module Noosfero::Factory else fast_insert(klass, data) end - obj = klass.last(:order => "id") + obj = klass.order(:id).last if options[:category] categories = options[:category] unless categories.is_a?(Array) @@ -65,8 +65,8 @@ module Noosfero::Factory ###### old stuff to be rearranged def create_admin_user(env) - admin_user = User.find_by_login('adminuser') || create_user('adminuser', :email => 'adminuser@noosfero.org', :password => 'adminuser', :password_confirmation => 'adminuser', :environment => env) - admin_role = Role.find_by_name('admin_role') || Role.create!(:name => 'admin_role', :permissions => ['view_environment_admin_panel','edit_environment_features', 'edit_environment_design', 'manage_environment_categories', 'manage_environment_roles', 'manage_environment_trusted_sites', 'manage_environment_validators', 'manage_environment_users', 'manage_environment_organizations', 'manage_environment_templates', 'manage_environment_licenses', 'edit_appearance']) + admin_user = User.find_by(login: 'adminuser') || create_user('adminuser', :email => 'adminuser@noosfero.org', :password => 'adminuser', :password_confirmation => 'adminuser', :environment => env) + admin_role = Role.find_by(name: 'admin_role') || Role.create!(:name => 'admin_role', :permissions => ['view_environment_admin_panel','edit_environment_features', 'edit_environment_design', 'manage_environment_categories', 'manage_environment_roles', 'manage_environment_trusted_sites', 'manage_environment_validators', 'manage_environment_users', 'manage_environment_organizations', 'manage_environment_templates', 'manage_environment_licenses', 'edit_appearance']) create(RoleAssignment, :accessor => admin_user.person, :role => admin_role, :resource => env) unless admin_user.person.role_assignments.map{|ra|[ra.role, ra.accessor, ra.resource]}.include?([admin_role, admin_user, env]) admin_user.login end @@ -132,7 +132,7 @@ module Noosfero::Factory values = names.map {|k| ActiveRecord::Base.send(:sanitize_sql_array, ['?', data[k]]) } sql = 'insert into %s(%s) values (%s)' % [klass.table_name, names.join(','), values.join(',')] klass.connection.execute(sql) - klass.last(:order => 'id') + klass.order(:id).last end def fast_insert_with_timestamps(klass, data) @@ -145,10 +145,10 @@ module Noosfero::Factory end def give_permission(user, permission, target) - user = Person.find_by_identifier(user) if user.kind_of?(String) + user = Person.find_by(identifier: user) if user.kind_of?(String) target ||= user i = 0 - while Role.find_by_name('test_role' + i.to_s) + while Role.find_by(name: 'test_role' + i.to_s) i+=1 end diff --git a/test/test_helper.rb b/test/test_helper.rb index b963dca..ed50fa3 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -181,7 +181,7 @@ class ActiveSupport::TestCase end def process_delayed_job_queue - silence_stream(STDOUT) do + silence_stream STDOUT do Delayed::Worker.new.work_off end end diff --git a/test/unit/abuse_complaint_test.rb b/test/unit/abuse_complaint_test.rb index 48a1598..8ad7ca6 100644 --- a/test/unit/abuse_complaint_test.rb +++ b/test/unit/abuse_complaint_test.rb @@ -24,15 +24,15 @@ class AbuseComplaintTest < ActiveSupport::TestCase assert_equal Task::Status::HIDDEN, abuse_complaint.status reported.environment.stubs(:reports_lower_bound).returns(2) - r1 = AbuseReport.new(:reason => 'some reason').tap do |a| + r1 = AbuseReport.new(:reason => 'some reason').tap do |a| a.reporter = p1 a.abuse_complaint = abuse_complaint end.save - r2 = AbuseReport.new(:reason => 'some reason').tap do |a| + r2 = AbuseReport.new(:reason => 'some reason').tap do |a| a.reporter = p2 a.abuse_complaint = abuse_complaint end.save - r3 = AbuseReport.new(:reason => 'some reason').tap do |a| + r3 = AbuseReport.new(:reason => 'some reason').tap do |a| a.reporter = p3 a.abuse_complaint = abuse_complaint end.save @@ -50,10 +50,10 @@ class AbuseComplaintTest < ActiveSupport::TestCase reported_id = reported.id abuse_complaint = AbuseComplaint.create!(:reported => reported) - assert AbuseComplaint.find_by_requestor_id(reported_id), "AbuseComplaint was not created!" + assert AbuseComplaint.find_by(requestor_id: reported_id), "AbuseComplaint was not created!" reported.destroy - refute AbuseComplaint.find_by_requestor_id(reported_id), "AbuseComplaint still exist!" + refute AbuseComplaint.find_by(requestor_id: reported_id), "AbuseComplaint still exist!" end end diff --git a/test/unit/action_tracker_notification_test.rb b/test/unit/action_tracker_notification_test.rb index 2a91915..513b7d1 100644 --- a/test/unit/action_tracker_notification_test.rb +++ b/test/unit/action_tracker_notification_test.rb @@ -81,8 +81,8 @@ class ActionTrackerNotificationTest < ActiveSupport::TestCase friend = fast_create(Person) person.add_friend(friend) process_delayed_job_queue - activity = ActionTracker::Record.find_last_by_verb 'new_friendship' - notification = ActionTrackerNotification.find_by_action_tracker_id activity.id + activity = ActionTracker::Record.where(verb: 'new_friendship').last + notification = ActionTrackerNotification.find_by action_tracker_id: activity.id comment = create(Comment, :source => activity, :author => person) assert_equal activity.comments, notification.comments diff --git a/test/unit/acts_as_customizable_test.rb b/test/unit/acts_as_customizable_test.rb index 7a9f57b..247e769 100644 --- a/test/unit/acts_as_customizable_test.rb +++ b/test/unit/acts_as_customizable_test.rb @@ -8,7 +8,7 @@ class ActsAsCustomizableTest < ActiveSupport::TestCase assert_difference 'CustomFieldValue.count' do person.custom_values = { "Blog" => { "value" => "www.blog.org", "public" => "0"} } person.save! - assert_equal 'www.blog.org', CustomFieldValue.find(:last, :conditions => {:customized_id => person.id}).value + assert_equal 'www.blog.org', CustomFieldValue.where(customized_id: person.id).last.value end end diff --git a/test/unit/approve_article_test.rb b/test/unit/approve_article_test.rb index 253fcc0..db5c002 100644 --- a/test/unit/approve_article_test.rb +++ b/test/unit/approve_article_test.rb @@ -301,7 +301,7 @@ class ApproveArticleTest < ActiveSupport::TestCase a = create(ApproveArticle, :article => article, :target => community, :requestor => profile) a.finish - approved_article = community.articles.find_by_name(article.name) + approved_article = community.articles.find_by(name: article.name) assert_equal approved_article, ActionTracker::Record.last.target end @@ -314,7 +314,7 @@ class ApproveArticleTest < ActiveSupport::TestCase a = create(ApproveArticle, :article => article, :target => person, :requestor => person) a.finish - approved_article = person.articles.find_by_name(article.name) + approved_article = person.articles.find_by(name: article.name) assert_equal approved_article, ActionTracker::Record.last.target end diff --git a/test/unit/article_categorization_test.rb b/test/unit/article_categorization_test.rb index 54ea08b..1b80e8b 100644 --- a/test/unit/article_categorization_test.rb +++ b/test/unit/article_categorization_test.rb @@ -32,7 +32,7 @@ class ArticleCategorizationTest < ActiveSupport::TestCase ArticleCategorization.add_category_to_article(c2, a) end - assert_equal 2, ArticleCategorization.find_all_by_article_id(a.id).size + assert_equal 2, ArticleCategorization.where(article_id: a.id).count end should 'not duplicate entry for category that is parent of two others' do diff --git a/test/unit/article_test.rb b/test/unit/article_test.rb index 1cadb59..c58aca3 100644 --- a/test/unit/article_test.rb +++ b/test/unit/article_test.rb @@ -597,7 +597,7 @@ class ArticleTest < ActiveSupport::TestCase a.name = 'new-name' a.save! - page = Article.find_by_old_path(old_path) + page = Article.find_by_old_path old_path assert_equal a.path, page.path end @@ -610,7 +610,7 @@ class ArticleTest < ActiveSupport::TestCase a1.save! a2 = p.articles.create!(:name => 'old-name') - page = Article.find_by_old_path(old_path) + page = Article.find_by_old_path old_path assert_equal a2.path, page.path end @@ -625,7 +625,7 @@ class ArticleTest < ActiveSupport::TestCase a2.name = 'other-new-name' a2.save! - page = Article.find_by_old_path(old_path) + page = Article.find_by_old_path old_path assert_equal a2.path, page.path end @@ -639,7 +639,7 @@ class ArticleTest < ActiveSupport::TestCase p2 = create_user('another_user').person - page = p2.articles.find_by_old_path(old_path) + page = p2.articles.find_by_old_path old_path assert_nil page end @@ -799,7 +799,7 @@ class ArticleTest < ActiveSupport::TestCase # also ignore parent with id = 0 assert_equal [c], a.categories_including_virtual - a = profile.articles.find_by_name 'a test article' + a = profile.articles.find_by name: 'a test article' assert_equal [c], a.categories end @@ -917,7 +917,7 @@ class ArticleTest < ActiveSupport::TestCase a = create(ApproveArticle, :article => article, :target => community, :requestor => profile) a.finish - published = community.articles.find_by_name('article name') + published = community.articles.find_by(name: 'article name') published.name = 'title with "quotes"' published.save assert_equal 'title with "quotes"', published.name @@ -988,8 +988,8 @@ class ArticleTest < ActiveSupport::TestCase activity = article.activity process_delayed_job_queue - assert_equal 3, ActionTrackerNotification.find_all_by_action_tracker_id(activity.id).count - assert_equivalent [p1,p2,community], ActionTrackerNotification.find_all_by_action_tracker_id(activity.id).map(&:profile) + assert_equal 3, ActionTrackerNotification.where(action_tracker_id: activity.id).count + assert_equivalent [p1,p2,community], ActionTrackerNotification.where(action_tracker_id: activity.id).map(&:profile) end should 'destroy activity when a published article is removed' do @@ -1090,17 +1090,17 @@ class ArticleTest < ActiveSupport::TestCase assert_equal [first_activity], ActionTracker::Record.where(verb: 'create_article') process_delayed_job_queue - assert_equal 2, ActionTrackerNotification.find_all_by_action_tracker_id(first_activity.id).count + assert_equal 2, ActionTrackerNotification.where(action_tracker_id: first_activity.id).count member_2 = fast_create(Person) community.add_member(member_2) article2 = create TinyMceArticle, :name => 'Tracked Article 2', :profile_id => community.id second_activity = article2.activity - assert_equivalent [first_activity, second_activity], ActionTracker::Record.find_all_by_verb('create_article') + assert_equivalent [first_activity, second_activity], ActionTracker::Record.where(verb: 'create_article') process_delayed_job_queue - assert_equal 3, ActionTrackerNotification.find_all_by_action_tracker_id(second_activity.id).count + assert_equal 3, ActionTrackerNotification.where(action_tracker_id: second_activity.id).count end should 'create notifications to friends when creating an article' do @@ -1122,16 +1122,16 @@ class ArticleTest < ActiveSupport::TestCase User.current = profile.user article = create TinyMceArticle, :name => 'Tracked Article 1', :profile_id => profile.id - assert_equal 1, ActionTracker::Record.find_all_by_verb('create_article').count + assert_equal 1, ActionTracker::Record.where(verb: 'create_article').count process_delayed_job_queue - assert_equal 2, ActionTrackerNotification.find_all_by_action_tracker_id(article.activity.id).count + assert_equal 2, ActionTrackerNotification.where(action_tracker_id: article.activity.id).count f2 = fast_create(Person) profile.add_friend(f2) article2 = create TinyMceArticle, :name => 'Tracked Article 2', :profile_id => profile.id - assert_equal 2, ActionTracker::Record.find_all_by_verb('create_article').count + assert_equal 2, ActionTracker::Record.where(verb: 'create_article').count process_delayed_job_queue - assert_equal 3, ActionTrackerNotification.find_all_by_action_tracker_id(article2.activity.id).count + assert_equal 3, ActionTrackerNotification.where(action_tracker_id: article2.activity.id).count end should 'destroy activity and notifications of friends when destroying an article' do @@ -1145,7 +1145,7 @@ class ArticleTest < ActiveSupport::TestCase activity = article.activity process_delayed_job_queue - assert_equal 2, ActionTrackerNotification.find_all_by_action_tracker_id(activity.id).count + assert_equal 2, ActionTrackerNotification.where(action_tracker_id: activity.id).count assert_difference 'ActionTrackerNotification.count', -2 do article.destroy @@ -1168,7 +1168,7 @@ class ArticleTest < ActiveSupport::TestCase activity = article.activity process_delayed_job_queue - assert_equal 3, ActionTrackerNotification.find_all_by_action_tracker_id(activity.id).count + assert_equal 3, ActionTrackerNotification.where(action_tracker_id: activity.id).count assert_difference 'ActionTrackerNotification.count', -3 do article.destroy @@ -2237,9 +2237,9 @@ class ArticleTest < ActiveSupport::TestCase p = fast_create(Person) assert_difference "a.reload.followers_count" do a.person_followers << p - end + end end - + should "decrement followers count when a person unfollow an article" do p = fast_create(Person) a = fast_create(Article, :profile_id => p) diff --git a/test/unit/community_test.rb b/test/unit/community_test.rb index cc19542..a17c849 100644 --- a/test/unit/community_test.rb +++ b/test/unit/community_test.rb @@ -39,10 +39,10 @@ class CommunityTest < ActiveSupport::TestCase Community.any_instance.stubs(:default_set_of_articles).returns([blog]) community = create(Community, :environment => Environment.default, :name => 'my new community') - assert_kind_of Blog, community.articles.find_by_path(blog.path) - assert community.articles.find_by_path(blog.path).published? - assert_kind_of RssFeed, community.articles.find_by_path(blog.feed.path) - assert community.articles.find_by_path(blog.feed.path).published? + assert_kind_of Blog, community.articles.find_by(path: blog.path) + assert community.articles.find_by(path: blog.path).published? + assert_kind_of RssFeed, community.articles.find_by(path: blog.feed.path) + assert community.articles.find_by(path: blog.feed.path).published? end should 'have contact_person' do diff --git a/test/unit/domain_test.rb b/test/unit/domain_test.rb index 3477474..7694eee 100644 --- a/test/unit/domain_test.rb +++ b/test/unit/domain_test.rb @@ -69,8 +69,8 @@ class DomainTest < ActiveSupport::TestCase def test_find_by_name Domain.delete_all fast_create(Domain, :name => 'example.net') - d1 = Domain.find_by_name('example.net') - d2 = Domain.find_by_name('www.example.net') + d1 = Domain.by_name('example.net') + d2 = Domain.by_name('www.example.net') refute d1.nil? refute d2.nil? assert d1 == d2 @@ -87,21 +87,21 @@ class DomainTest < ActiveSupport::TestCase def test_environment # domain directly linked to Environment - domain = Domain.find_by_name('colivre.net') + domain = Domain.by_name('colivre.net') assert_kind_of Environment, domain.owner assert_kind_of Environment, domain.environment # domain linked to Profile - domain = Domain.find_by_name('johndoe.net') + domain = Domain.by_name('johndoe.net') assert_kind_of Profile, domain.owner assert_kind_of Environment, domain.environment end def test_profile # domain linked to profile - assert_not_nil Domain.find_by_name('johndoe.net').profile + assert_not_nil Domain.by_name('johndoe.net').profile # domain linked to Environment - assert_nil Domain.find_by_name('colivre.net').profile + assert_nil Domain.by_name('colivre.net').profile end def test_hosted_domain diff --git a/test/unit/email_template_test.rb b/test/unit/email_template_test.rb index e44d4a6..23e4362 100644 --- a/test/unit/email_template_test.rb +++ b/test/unit/email_template_test.rb @@ -6,7 +6,7 @@ class EmailTemplateTest < ActiveSupport::TestCase EmailTemplate.create!(:template_type => :type1, :name => 'template1') EmailTemplate.create!(:template_type => :type2, :name => 'template2') EmailTemplate.create!(:template_type => :type2, :name => 'template3') - assert_equal ['template2', 'template3'], EmailTemplate.find_all_by_template_type(:type2).map(&:name) + assert_equal ['template2', 'template3'], EmailTemplate.where(template_type: :type2).map(&:name) end should 'parse body using params' do diff --git a/test/unit/enterprise_test.rb b/test/unit/enterprise_test.rb index 41a0c42..000b329 100644 --- a/test/unit/enterprise_test.rb +++ b/test/unit/enterprise_test.rb @@ -76,8 +76,8 @@ class EnterpriseTest < ActiveSupport::TestCase Enterprise.any_instance.expects(:default_set_of_articles).returns([blog]) enterprise = create(Enterprise, :name => 'my test enterprise', :identifier => 'myenterprise') - assert_kind_of Blog, enterprise.articles.find_by_path(blog.path) - assert_kind_of RssFeed, enterprise.articles.find_by_path(blog.feed.path) + assert_kind_of Blog, enterprise.articles.find_by(path: blog.path) + assert_kind_of RssFeed, enterprise.articles.find_by(path: blog.feed.path) end should 'create default set of blocks' do @@ -206,13 +206,13 @@ class EnterpriseTest < ActiveSupport::TestCase should 'create EnterpriseActivation task when creating with enabled = false' do EnterpriseActivation.delete_all ent = create(Enterprise, :name => 'test enteprise', :identifier => 'test_ent', :enabled => false) - assert_equal [ent], EnterpriseActivation.find(:all).map(&:enterprise) + assert_equal [ent], EnterpriseActivation.all.map(&:enterprise) end should 'create EnterpriseActivation with 7-characters codes' do EnterpriseActivation.delete_all create(Enterprise, :name => 'test enteprise', :identifier => 'test_ent', :enabled => false) - assert_equal 7, EnterpriseActivation.find(:first).code.size + assert_equal 7, EnterpriseActivation.first.code.size end should 'not create activation task when enabled = true' do diff --git a/test/unit/environment_mailing_test.rb b/test/unit/environment_mailing_test.rb index c312db5..7537b94 100644 --- a/test/unit/environment_mailing_test.rb +++ b/test/unit/environment_mailing_test.rb @@ -86,7 +86,7 @@ class EnvironmentMailingTest < ActiveSupport::TestCase mailing = create_mailing(environment, :person => person_1) process_delayed_job_queue - assert mailing.mailing_sents.find_by_person_id(person_1.id) + assert mailing.mailing_sents.find_by(person_id: person_1.id) end should 'return false if did not sent mailing to a recipient' do @@ -95,7 +95,7 @@ class EnvironmentMailingTest < ActiveSupport::TestCase mailing = create_mailing(environment, :person => person_1) process_delayed_job_queue - refute mailing.mailing_sents.find_by_person_id(recipient.id) + refute mailing.mailing_sents.find_by(person_id: recipient.id) end def new_mailing(environment) diff --git a/test/unit/environment_test.rb b/test/unit/environment_test.rb index 1c57be7..8ca3449 100644 --- a/test/unit/environment_test.rb +++ b/test/unit/environment_test.rb @@ -359,16 +359,16 @@ class EnvironmentTest < ActiveSupport::TestCase end should 'have admin role' do - Role.expects(:find_by_key_and_environment_id).with('environment_administrator', Environment.default.id).returns(Role.new) + Role.expects(:find_by).with(key: 'environment_administrator', environment_id: Environment.default.id).returns(Role.new) assert_kind_of Role, Environment::Roles.admin(Environment.default.id) end should 'create environment and profile default roles' do env = Environment.default - assert_equal 'Environment', env.roles.find_by_key('environment_administrator').kind - assert_equal 'Profile', env.roles.find_by_key('profile_admin').kind - assert_equal 'Profile', env.roles.find_by_key('profile_member').kind - assert_equal 'Profile', env.roles.find_by_key('profile_moderator').kind + assert_equal 'Environment', env.roles.find_by(key: 'environment_administrator').kind + assert_equal 'Profile', env.roles.find_by(key: 'profile_admin').kind + assert_equal 'Profile', env.roles.find_by(key: 'profile_member').kind + assert_equal 'Profile', env.roles.find_by(key: 'profile_moderator').kind end should 'be able to add admins easily' do diff --git a/test/unit/folder_test.rb b/test/unit/folder_test.rb index 678661e..6c6514b 100644 --- a/test/unit/folder_test.rb +++ b/test/unit/folder_test.rb @@ -98,7 +98,7 @@ class FolderTest < ActiveSupport::TestCase a = create(ApproveArticle, :article => image, :target => community, :requestor => person, :article_parent => folder) a.finish - assert_includes folder.images(true), community.articles.find_by_name('rails.png') + assert_includes folder.images(true), community.articles.find_by(name: 'rails.png') end should 'not let pass javascript in the name' do diff --git a/test/unit/gallery_test.rb b/test/unit/gallery_test.rb index 45a7bbf..5c18fde 100644 --- a/test/unit/gallery_test.rb +++ b/test/unit/gallery_test.rb @@ -107,7 +107,7 @@ class GalleryTest < ActiveSupport::TestCase a = create(ApproveArticle, :article => i, :target => c, :requestor => p, :article_parent => gallery) a.finish - assert_includes gallery.images(true), c.articles.find_by_name('rails.png') + assert_includes gallery.images(true), c.articles.find_by(name: 'rails.png') end should 'not let pass javascript in the body' do diff --git a/test/unit/moderate_user_registration_test.rb b/test/unit/moderate_user_registration_test.rb index 7f632ad..ca2d442 100644 --- a/test/unit/moderate_user_registration_test.rb +++ b/test/unit/moderate_user_registration_test.rb @@ -17,6 +17,6 @@ class ModerateUserRegistrationTest < ActiveSupport::TestCase t.save! refute user.activated? t.perform - assert environment.users.find_by_id(user.id).activated? + assert environment.users.find_by(id: user.id).activated? end end diff --git a/test/unit/notify_activity_to_profiles_job_test.rb b/test/unit/notify_activity_to_profiles_job_test.rb index 57e1ad9..311113d 100644 --- a/test/unit/notify_activity_to_profiles_job_test.rb +++ b/test/unit/notify_activity_to_profiles_job_test.rb @@ -19,7 +19,7 @@ class NotifyActivityToProfilesJobTest < ActiveSupport::TestCase assert_equal 1, ActionTrackerNotification.count [community].each do |profile| - notification = ActionTrackerNotification.find_by_profile_id profile.id + notification = ActionTrackerNotification.find_by profile_id: profile.id assert_equal action_tracker, notification.action_tracker end end @@ -41,7 +41,7 @@ class NotifyActivityToProfilesJobTest < ActiveSupport::TestCase assert_equal 3, ActionTrackerNotification.count [person, p1, p2].each do |profile| - notification = ActionTrackerNotification.find_by_profile_id profile.id + notification = ActionTrackerNotification.find_by profile_id: profile.id assert_equal action_tracker, notification.action_tracker end end @@ -61,7 +61,7 @@ class NotifyActivityToProfilesJobTest < ActiveSupport::TestCase assert_equal 4, ActionTrackerNotification.count [person, community, m1, m2].each do |profile| - notification = ActionTrackerNotification.find_by_profile_id profile.id + notification = ActionTrackerNotification.find_by profile_id: profile.id assert_equal action_tracker, notification.action_tracker end end @@ -83,7 +83,7 @@ class NotifyActivityToProfilesJobTest < ActiveSupport::TestCase assert_equal 6, ActionTrackerNotification.count [person, community, p1, p2, m1, m2].each do |profile| - notification = ActionTrackerNotification.find_by_profile_id profile.id + notification = ActionTrackerNotification.find_by profile_id: profile.id assert_equal action_tracker, notification.action_tracker end end @@ -105,11 +105,11 @@ class NotifyActivityToProfilesJobTest < ActiveSupport::TestCase assert_equal 1, ActionTrackerNotification.count [person, p1, p2, m1, m2].each do |profile| - notification = ActionTrackerNotification.find_by_profile_id profile.id + notification = ActionTrackerNotification.find_by profile_id: profile.id assert notification.nil? end - notification = ActionTrackerNotification.find_by_profile_id private_community.id + notification = ActionTrackerNotification.find_by profile_id: private_community.id assert_equal action_tracker, notification.action_tracker end @@ -130,7 +130,7 @@ class NotifyActivityToProfilesJobTest < ActiveSupport::TestCase assert_equal 5, ActionTrackerNotification.count [person, p1, p2, m1, m2].each do |profile| - notification = ActionTrackerNotification.find_by_profile_id profile.id + notification = ActionTrackerNotification.find_by profile_id: profile.id assert_equal action_tracker, notification.action_tracker end end diff --git a/test/unit/organization_mailing_test.rb b/test/unit/organization_mailing_test.rb index 1baedbc..f050d5f 100644 --- a/test/unit/organization_mailing_test.rb +++ b/test/unit/organization_mailing_test.rb @@ -112,7 +112,7 @@ class OrganizationMailingTest < ActiveSupport::TestCase member = Person['user_one'] mailing = create(OrganizationMailing, :source => community, :subject => 'Hello', :body => 'We have some news', :person => person) process_delayed_job_queue - assert mailing.mailing_sents.find_by_person_id(member.id) + assert mailing.mailing_sents.find_by(person_id: member.id) end should 'return false if did not sent mailing to a recipient' do @@ -120,7 +120,7 @@ class OrganizationMailingTest < ActiveSupport::TestCase mailing = create(OrganizationMailing, :source => community, :subject => 'Hello', :body => 'We have some news', :person => person) process_delayed_job_queue - refute mailing.mailing_sents.find_by_person_id(recipient.id) + refute mailing.mailing_sents.find_by(person_id: recipient.id) end protected diff --git a/test/unit/person_test.rb b/test/unit/person_test.rb index 4a5e045..440a8f6 100644 --- a/test/unit/person_test.rb +++ b/test/unit/person_test.rb @@ -180,10 +180,10 @@ class PersonTest < ActiveSupport::TestCase Person.any_instance.stubs(:default_set_of_articles).returns([blog]) person = create(User).person - assert_kind_of Blog, person.articles.find_by_path(blog.path) - assert person.articles.find_by_path(blog.path).published? - assert_kind_of RssFeed, person.articles.find_by_path(blog.feed.path) - assert person.articles.find_by_path(blog.feed.path).published? + assert_kind_of Blog, person.articles.find_by(path: blog.path) + assert person.articles.find_by(path: blog.path).published? + assert_kind_of RssFeed, person.articles.find_by(path: blog.feed.path) + assert person.articles.find_by(path: blog.feed.path).published? end should 'create a default set of blocks' do @@ -831,9 +831,9 @@ class PersonTest < ActiveSupport::TestCase should "destroy scrap if sender was removed" do person = fast_create(Person) scrap = fast_create(Scrap, :sender_id => person.id) - assert_not_nil Scrap.find_by_id(scrap.id) + assert_not_nil Scrap.find_by(id: scrap.id) person.destroy - assert_nil Scrap.find_by_id(scrap.id) + assert_nil Scrap.find_by(id: scrap.id) end should "the tracked action be notified to person friends and herself" do @@ -1123,7 +1123,7 @@ class PersonTest < ActiveSupport::TestCase organization.add_admin(person) assert person.is_last_admin_leaving?(organization, []) - refute person.is_last_admin_leaving?(organization, [Role.find_by_key('profile_admin')]) + refute person.is_last_admin_leaving?(organization, [Role.find_by(key: 'profile_admin')]) end should 'return unique members of a community' do @@ -1467,13 +1467,13 @@ class PersonTest < ActiveSupport::TestCase should 'merge memberships of plugins to original memberships' do class Plugin1 < Noosfero::Plugin def person_memberships(person) - Profile.memberships_of(Person.find_by_identifier('person1')) + Profile.memberships_of(Person.find_by(identifier: 'person1')) end end class Plugin2 < Noosfero::Plugin def person_memberships(person) - Profile.memberships_of(Person.find_by_identifier('person2')) + Profile.memberships_of(Person.find_by(identifier: 'person2')) end end Noosfero::Plugin.stubs(:all).returns(['PersonTest::Plugin1', 'PersonTest::Plugin2']) diff --git a/test/unit/product_test.rb b/test/unit/product_test.rb index b156c05..2cce599 100644 --- a/test/unit/product_test.rb +++ b/test/unit/product_test.rb @@ -368,7 +368,7 @@ class ProductTest < ActiveSupport::TestCase refute product.price_details.empty? product.update_price_details([{:production_cost_id => cost.id, :price => 20}, {:production_cost_id => cost2.id, :price => 30}]) - assert_equal 20, product.price_details.find_by_production_cost_id(cost.id).price + assert_equal 20, product.price_details.find_by(production_cost_id: cost.id).price assert_equal 2, Product.find(product.id).price_details.size end diff --git a/test/unit/profile_categorization_test.rb b/test/unit/profile_categorization_test.rb index 9a5b3d4..93d8574 100644 --- a/test/unit/profile_categorization_test.rb +++ b/test/unit/profile_categorization_test.rb @@ -9,7 +9,7 @@ class ProfileCategorizationTest < ActiveSupport::TestCase person.save! assert_includes person.categories, cat assert_includes cat.people, person - assert_equal [cat.id], person.category_ids + assert_equal [cat.id], person.category_ids end should 'create instances for the entire hierarchy' do @@ -24,7 +24,7 @@ class ProfileCategorizationTest < ActiveSupport::TestCase ProfileCategorization.add_category_to_profile(c2, p) end - assert_equal 2, ProfileCategorization.find_all_by_profile_id(p.id).size + assert_equal 2, ProfileCategorization.where(profile_id: p.id).count end should 'not duplicate entry for category that is parent of two others' do diff --git a/test/unit/profile_test.rb b/test/unit/profile_test.rb index f735ca3..538d1de 100644 --- a/test/unit/profile_test.rb +++ b/test/unit/profile_test.rb @@ -319,17 +319,17 @@ class ProfileTest < ActiveSupport::TestCase end should 'have administator role' do - Role.expects(:find_by_key_and_environment_id).with('profile_admin', Environment.default.id).returns(Role.new) + Role.expects(:find_by).with(key: 'profile_admin', environment_id: Environment.default.id).returns(Role.new) assert_kind_of Role, Profile::Roles.admin(Environment.default.id) end should 'have member role' do - Role.expects(:find_by_key_and_environment_id).with('profile_member', Environment.default.id).returns(Role.new) + Role.expects(:find_by).with(key: 'profile_member', environment_id: Environment.default.id).returns(Role.new) assert_kind_of Role, Profile::Roles.member(Environment.default.id) end should 'have moderator role' do - Role.expects(:find_by_key_and_environment_id).with('profile_moderator', Environment.default.id).returns(Role.new) + Role.expects(:find_by).with(key: 'profile_moderator', environment_id: Environment.default.id).returns(Role.new) assert_kind_of Role, Profile::Roles.moderator(Environment.default.id) end @@ -434,14 +434,14 @@ class ProfileTest < ActiveSupport::TestCase should 'not advertise articles created together with the profile' do Profile.any_instance.stubs(:default_set_of_articles).returns([Article.new(:name => 'home'), RssFeed.new(:name => 'feed')]) profile = create(Profile) - refute profile.articles.find_by_path('home').advertise? - refute profile.articles.find_by_path('feed').advertise? + refute profile.articles.find_by(path: 'home').advertise? + refute profile.articles.find_by(path: 'feed').advertise? end should 'advertise article after update' do Profile.any_instance.stubs(:default_set_of_articles).returns([Article.new(:name => 'home')]) profile = create(Profile) - article = profile.articles.find_by_path('home') + article = profile.articles.find_by(path: 'home') refute article.advertise? article.name = 'Changed name' article.save! @@ -1033,7 +1033,7 @@ class ProfileTest < ActiveSupport::TestCase p.apply_template(template) - assert_not_nil p.articles.find_by_name('template article') + assert_not_nil p.articles.find_by(name: 'template article') end should 'rename existing articles when applying template' do @@ -1049,8 +1049,8 @@ class ProfileTest < ActiveSupport::TestCase p.apply_template(template) - assert_not_nil p.articles.find_by_name('some article 2') - assert_not_nil p.articles.find_by_name('some article') + assert_not_nil p.articles.find_by(name: 'some article 2') + assert_not_nil p.articles.find_by(name: 'some article') end should 'copy header when applying template' do @@ -1326,7 +1326,7 @@ class ProfileTest < ActiveSupport::TestCase task2 = Task.create!(:requestor => person, :target => another) person.stubs(:is_admin?).with(other).returns(true) - Environment.find(:all).select{|i| i != other }.each do |env| + Environment.all.select{|i| i != other }.each do |env| person.stubs(:is_admin?).with(env).returns(false) end @@ -1778,9 +1778,9 @@ class ProfileTest < ActiveSupport::TestCase should "destroy scrap if receiver was removed" do person = fast_create(Person) scrap = fast_create(Scrap, :receiver_id => person.id) - assert_not_nil Scrap.find_by_id(scrap.id) + assert_not_nil Scrap.find_by(id: scrap.id) person.destroy - assert_nil Scrap.find_by_id(scrap.id) + assert_nil Scrap.find_by(id: scrap.id) end should 'have forum' do @@ -1928,13 +1928,13 @@ class ProfileTest < ActiveSupport::TestCase should 'merge members of plugins to original members' do class Plugin1 < Noosfero::Plugin def organization_members(profile) - Person.members_of(Community.find_by_identifier('community1')) + Person.members_of(Community.find_by(identifier: 'community1')) end end class Plugin2 < Noosfero::Plugin def organization_members(profile) - Person.members_of(Community.find_by_identifier('community2')) + Person.members_of(Community.find_by(identifier: 'community2')) end end Noosfero::Plugin.stubs(:all).returns(['ProfileTest::Plugin1', 'ProfileTest::Plugin2']) @@ -2148,7 +2148,7 @@ class ProfileTest < ActiveSupport::TestCase suggested_person = fast_create(Person) suggestion = ProfileSuggestion.create(:person => person, :suggestion => suggested_person, :enabled => true) - assert_difference 'ProfileSuggestion.find_all_by_suggestion_id(suggested_person.id).count', -1 do + assert_difference 'ProfileSuggestion.where(suggestion_id: suggested_person.id).count', -1 do suggested_person.destroy end end diff --git a/test/unit/text_article_test.rb b/test/unit/text_article_test.rb index b4e88bd..6b0d424 100644 --- a/test/unit/text_article_test.rb +++ b/test/unit/text_article_test.rb @@ -11,7 +11,7 @@ class TextArticleTest < ActiveSupport::TestCase should 'found TextileArticle by TextArticle class' do person = create_user('testuser').person article = fast_create(TextileArticle, :name => 'textile article test', :profile_id => person.id) - assert_includes TextArticle.find(:all), article + assert_includes TextArticle.all, article end should 'be translatable' do diff --git a/test/unit/uploaded_file_test.rb b/test/unit/uploaded_file_test.rb index 4c8e0a9..8766703 100644 --- a/test/unit/uploaded_file_test.rb +++ b/test/unit/uploaded_file_test.rb @@ -320,7 +320,7 @@ class UploadedFileTest < ActiveSupport::TestCase should 'use gallery as target for action tracker' do gallery = fast_create(Gallery, :profile_id => profile.id) image = create(UploadedFile, :uploaded_data => fixture_file_upload('/files/rails.png', 'image/png'), :parent => gallery, :profile => profile) - activity = ActionTracker::Record.find_last_by_verb 'upload_image' + activity = ActionTracker::Record.where(verb: 'upload_image').last assert_equal gallery, activity.target end @@ -329,10 +329,10 @@ class UploadedFileTest < ActiveSupport::TestCase gallery = fast_create(Gallery, :profile_id => profile.id) image1 = UploadedFile.create!(:uploaded_data => fixture_file_upload('/files/rails.png', 'image/png'), :parent => gallery, :profile => profile) - assert_equal 1, ActionTracker::Record.find_all_by_verb('upload_image').count + assert_equal 1, ActionTracker::Record.where(verb: 'upload_image').count image2 = UploadedFile.create!(:uploaded_data => fixture_file_upload('/files/other-pic.jpg', 'image/jpg'), :parent => gallery, :profile => profile) - assert_equal 1, ActionTracker::Record.find_all_by_verb('upload_image').count + assert_equal 1, ActionTracker::Record.where(verb: 'upload_image').count end { diff --git a/test/unit/user_test.rb b/test/unit/user_test.rb index 2e01880..4cfb176 100644 --- a/test/unit/user_test.rb +++ b/test/unit/user_test.rb @@ -164,9 +164,9 @@ class UserTest < ActiveSupport::TestCase def test_should_create_person_when_creating_user count = Person.count - refute Person.find_by_identifier('lalala') + refute Person.find_by(identifier: 'lalala') new_user(:login => 'lalala', :email => 'lalala@example.com') - assert Person.find_by_identifier('lalala') + assert Person.find_by(identifier: 'lalala') end should 'set the same environment for user and person objects' do @@ -178,9 +178,9 @@ class UserTest < ActiveSupport::TestCase def test_should_destroy_person_when_destroying_user user = new_user(:login => 'lalala', :email => 'lalala@example.com') - assert Person.find_by_identifier('lalala') + assert Person.find_by(identifier: 'lalala') user.destroy - refute Person.find_by_identifier('lalala') + refute Person.find_by(identifier: 'lalala') end def test_should_encrypt_password_with_salted_sha1 diff --git a/vendor/plugins/access_control/lib/acts_as_accessible.rb b/vendor/plugins/access_control/lib/acts_as_accessible.rb index ee48a8d..0b1dc3b 100644 --- a/vendor/plugins/access_control/lib/acts_as_accessible.rb +++ b/vendor/plugins/access_control/lib/acts_as_accessible.rb @@ -32,7 +32,7 @@ module ActsAsAccessible end def roles - Role.find_all_by_environment_id(environment.id).select do |r| + Role.where(environment_id: environment.id).select do |r| r.permissions.any?{ |p| PERMISSIONS[self.class.base_class.name].include?(p) } end end diff --git a/vendor/plugins/access_control/lib/acts_as_accessor.rb b/vendor/plugins/access_control/lib/acts_as_accessor.rb index 35f27a6..198eaa0 100644 --- a/vendor/plugins/access_control/lib/acts_as_accessor.rb +++ b/vendor/plugins/access_control/lib/acts_as_accessor.rb @@ -23,7 +23,7 @@ module ActsAsAccessor def add_role(role, resource, attributes = {}) attributes = role_attributes(role, resource).merge attributes - if RoleAssignment.find(:all, :conditions => attributes).empty? + if RoleAssignment.find_by(attributes).nil? ra = RoleAssignment.new(attributes) role_assignments << ra resource.role_assignments << ra diff --git a/vendor/plugins/action_tracker/lib/action_tracker.rb b/vendor/plugins/action_tracker/lib/action_tracker.rb index f41d81b..ef8e414 100644 --- a/vendor/plugins/action_tracker/lib/action_tracker.rb +++ b/vendor/plugins/action_tracker/lib/action_tracker.rb @@ -73,7 +73,8 @@ module ActionTracker end def acts_as_trackable(options = {}) - has_many :tracked_actions, { :class_name => "ActionTracker::Record", :order => "updated_at DESC", :foreign_key => :user_id, :dependent => :destroy }.merge(options) + has_many :tracked_actions, -> { order 'updated_at DESC' }, + {class_name: "ActionTracker::Record", foreign_key: :user_id, dependent: :destroy }.merge(options) send :include, InstanceMethods end end diff --git a/vendor/plugins/acts_as_list/lib/active_record/acts/list.rb b/vendor/plugins/acts_as_list/lib/active_record/acts/list.rb index 0e3d298..0badd9a 100644 --- a/vendor/plugins/acts_as_list/lib/active_record/acts/list.rb +++ b/vendor/plugins/acts_as_list/lib/active_record/acts/list.rb @@ -31,46 +31,22 @@ module ActiveRecord # to give it an entire string that is interpolated if you need a tighter scope than just a foreign key. # Example: acts_as_list :scope => 'todo_list_id = #{todo_list_id} AND completed = 0' def acts_as_list(options = {}) - configuration = { :column => "position", :scope => "1 = 1" } + configuration = { column: 'position' } configuration.update(options) if options.is_a?(Hash) - configuration[:scope] = "#{configuration[:scope]}_id".intern if configuration[:scope].is_a?(Symbol) && configuration[:scope].to_s !~ /_id$/ - - if configuration[:scope].is_a?(Symbol) - scope_condition_method = %( - def scope_condition - self.class.send(:sanitize_sql_hash_for_conditions, { :#{configuration[:scope].to_s} => send(:#{configuration[:scope].to_s}) }) - end - ) - elsif configuration[:scope].is_a?(Array) - scope_condition_method = %( - def scope_condition - attrs = %w(#{configuration[:scope].join(" ")}).inject({}) do |memo,column| - memo[column.intern] = send(column.intern); memo - end - self.class.send(:sanitize_sql_hash_for_conditions, attrs) - end - ) - else - scope_condition_method = "def scope_condition() \"#{configuration[:scope]}\" end" - end - - class_eval <<-EOV - include ActiveRecord::Acts::List::InstanceMethods + class_attribute :acts_as_list_class + self.acts_as_list_class = self - def acts_as_list_class - ::#{self.name} - end + include ActiveRecord::Acts::List::InstanceMethods - def position_column - '#{configuration[:column]}' - end + define_method :position_column do + configuration[:column] + end - #{scope_condition_method} + scope :acts_as_list_scope, configuration[:scope] - before_destroy :decrement_positions_on_lower_items - before_create :add_to_list_bottom - EOV + before_destroy :decrement_positions_on_lower_items + before_create :add_to_list_bottom end end @@ -159,13 +135,19 @@ module ActiveRecord # Return the next higher item in the list. def higher_item return nil unless in_list? - acts_as_list_class.where("#{scope_condition} AND #{position_column} = #{(send(position_column).to_i - 1).to_s}").first + acts_as_list_class + .acts_as_list_scope(self) + .where(position_column => send(position_column).to_i - 1) + .first end # Return the next lower item in the list. def lower_item return nil unless in_list? - acts_as_list_class.where("#{scope_condition} AND #{position_column} = #{(send(position_column).to_i + 1).to_s}").first + acts_as_list_class + .acts_as_list_scope(self) + .where(position_column => send(position_column).to_i + 1) + .first end # Test if this record is in a list @@ -182,9 +164,6 @@ module ActiveRecord self[position_column] = bottom_position_in_list.to_i + 1 end - # Overwrite this method to define the scope of the list changes - def scope_condition() "1" end - # Returns the bottom position number in the list. # bottom_position_in_list # => 2 def bottom_position_in_list(except = nil) @@ -194,9 +173,11 @@ module ActiveRecord # Returns the bottom item def bottom_item(except = nil) - conditions = scope_condition - conditions = "#{conditions} AND #{self.class.primary_key} != #{except.id}" if except - acts_as_list_class.where(conditions).order("#{position_column} DESC").first + conditions = "#{self.class.primary_key} != #{except.id}" if except + acts_as_list_class + .acts_as_list_scope(self) + .where(conditions).order("#{position_column} DESC") + .first end # Forces item to assume the bottom position in the list. @@ -211,39 +192,43 @@ module ActiveRecord # This has the effect of moving all the higher items up one. def decrement_positions_on_higher_items(position) - acts_as_list_class.update_all( - "#{position_column} = (#{position_column} - 1)", "#{scope_condition} AND #{position_column} <= #{position}" - ) + acts_as_list_class + .acts_as_list_scope(self) + .where("#{position_column} <= #{position}") + .update_all("#{position_column} = (#{position_column} - 1)") end # This has the effect of moving all the lower items up one. def decrement_positions_on_lower_items return unless in_list? - acts_as_list_class.update_all( - "#{position_column} = (#{position_column} - 1)", "#{scope_condition} AND #{position_column} > #{send(position_column).to_i}" - ) + acts_as_list_class + .acts_as_list_scope(self) + .where("#{position_column} > #{send(position_column).to_i}") + .update_all("#{position_column} = (#{position_column} - 1)") end # This has the effect of moving all the higher items down one. def increment_positions_on_higher_items return unless in_list? - acts_as_list_class.update_all( - "#{position_column} = (#{position_column} + 1)", "#{scope_condition} AND #{position_column} < #{send(position_column).to_i}" - ) + acts_as_list_class + .acts_as_list_scope(self) + .where("#{position_column} < #{send(position_column).to_i}") + .update_all("#{position_column} = (#{position_column} + 1)") end # This has the effect of moving all the lower items down one. def increment_positions_on_lower_items(position) - acts_as_list_class.update_all( - "#{position_column} = (#{position_column} + 1)", "#{scope_condition} AND #{position_column} >= #{position}" - ) + acts_as_list_class + .acts_as_list_scope(self) + .where("#{position_column} >= #{position}") + .update_all("#{position_column} = (#{position_column} + 1)") end # Increments position (position_column) of all items in the list. def increment_positions_on_all_items - acts_as_list_class.update_all( - "#{position_column} = (#{position_column} + 1)", "#{scope_condition}" - ) + acts_as_list_class + .acts_as_list_scope(self) + .update_all("#{position_column} = (#{position_column} + 1)") end def insert_at_position(position) diff --git a/vendor/plugins/acts_as_tree/lib/active_record/acts/tree.rb b/vendor/plugins/acts_as_tree/lib/active_record/acts/tree.rb index 1f00e90..da7523e 100644 --- a/vendor/plugins/acts_as_tree/lib/active_record/acts/tree.rb +++ b/vendor/plugins/acts_as_tree/lib/active_record/acts/tree.rb @@ -43,20 +43,21 @@ module ActiveRecord configuration = { :foreign_key => "parent_id", :order => nil, :counter_cache => nil } configuration.update(options) if options.is_a?(Hash) - belongs_to :parent, :class_name => name, :foreign_key => configuration[:foreign_key], :counter_cache => configuration[:counter_cache] - has_many :children, :class_name => name, :foreign_key => configuration[:foreign_key], :order => configuration[:order], :dependent => :destroy + belongs_to :parent, class_name: name, foreign_key: configuration[:foreign_key], counter_cache: configuration[:counter_cache] + has_many :children, -> { order configuration[:order] }, + class_name: name, foreign_key: configuration[:foreign_key], dependent: :destroy - class_eval <<-EOV - include ActiveRecord::Acts::Tree::InstanceMethods + include ActiveRecord::Acts::Tree::InstanceMethods - def self.roots - find(:all, :conditions => "#{configuration[:foreign_key]} IS NULL", :order => #{configuration[:order].nil? ? "nil" : %Q{"#{configuration[:order]}"}}) - end + scope :roots, -> { + s = where("#{configuration[:foreign_key]} IS NULL") + s = s.order configuration[:order] if configuration[:order] + s + } - def self.root - find(:first, :conditions => "#{configuration[:foreign_key]} IS NULL", :order => #{configuration[:order].nil? ? "nil" : %Q{"#{configuration[:order]}"}}) - end - EOV + def self.root + self.roots.first + end end end diff --git a/vendor/plugins/kandadaboggu-vote_fu/examples/users_controller.rb b/vendor/plugins/kandadaboggu-vote_fu/examples/users_controller.rb index 091351c..7be36f4 100644 --- a/vendor/plugins/kandadaboggu-vote_fu/examples/users_controller.rb +++ b/vendor/plugins/kandadaboggu-vote_fu/examples/users_controller.rb @@ -1,10 +1,10 @@ # I usually use the user class from restful_authentication as my principle voter class -# There are generally no changes required to support voting in this controller. +# There are generally no changes required to support voting in this controller. class UsersController < ApplicationController # Be sure to include AuthenticationSystem in Application Controller instead include AuthenticatedSystem - + # Protect these actions behind an admin login before_filter :admin_required, :only => [:suspend, :unsuspend, :destroy, :purge] before_filter :find_user, :only => [:suspend, :unsuspend, :destroy, :purge, :show] @@ -18,7 +18,7 @@ class UsersController < ApplicationController # GET /users/:id def show end - + def create cookies.delete :auth_token @@ -36,7 +36,7 @@ class UsersController < ApplicationController def activate unless params[:activation_code].blank? - self.current_user = User.find_by_activation_code(params[:activation_code]) + self.current_user = User.find_by(activation_code: params[:activation_code]) if logged_in? && !current_user.active? current_user.activate! flash[:notice] = "Signup complete!" @@ -45,16 +45,16 @@ class UsersController < ApplicationController flash[:error] = "Sorry, we couldn't find that activation code. Please cut and paste your activation code into the space at left." end end - # render activate.html.erb + # render activate.html.erb end def suspend - @user.suspend! + @user.suspend! redirect_to users_path end def unsuspend - @user.unsuspend! + @user.unsuspend! redirect_to users_path end diff --git a/vendor/plugins/kandadaboggu-vote_fu/lib/acts_as_voteable.rb b/vendor/plugins/kandadaboggu-vote_fu/lib/acts_as_voteable.rb index 26cdcce..1516e6b 100644 --- a/vendor/plugins/kandadaboggu-vote_fu/lib/acts_as_voteable.rb +++ b/vendor/plugins/kandadaboggu-vote_fu/lib/acts_as_voteable.rb @@ -72,7 +72,7 @@ module Juixe # :at_least_total - Item must have at least X votes total # :at_most_total - Item may not have more than X votes total def tally(options = {}) - find(:all, options_for_tally({:order =>"total DESC" }.merge(options))) + order("total DESC").all options_for_tally(options) end def options_for_tally (options = {}) diff --git a/vendor/plugins/kandadaboggu-vote_fu/lib/has_karma.rb b/vendor/plugins/kandadaboggu-vote_fu/lib/has_karma.rb index 53473bd..091d708 100644 --- a/vendor/plugins/kandadaboggu-vote_fu/lib/has_karma.rb +++ b/vendor/plugins/kandadaboggu-vote_fu/lib/has_karma.rb @@ -27,42 +27,34 @@ module PeteOnRails end end end - + # This module contains class methods module SingletonMethods - + ## Not yet implemented. Don't use it! # Find the most popular users def find_most_karmic - find(:all) + all end - + end - + # This module contains instance methods module InstanceMethods def karma(options = {}) - #FIXME cannot have 2 models imapcting the karma simultaneously - # count the total number of votes on all of the voteable objects that are related to this object - #2009-01-30 GuillaumeNM The following line is not SQLite3 compatible, because boolean are stored as 'f' or 't', not '1', or '0' - #self.karma_voteable.sum(:vote, options_for_karma(options)) - #self.karma_voteable.find(:all, options_for_karma(options)).length karma_value = 0 self.class.karmatic_objects.each do |object| - karma_value += object.find(:all, options_for_karma(object, options)).length + karma_value += object + .where("u.id = ? AND vote = ?" , self[:id] , true) + .joins("inner join votes v on #{object.table_name}.id = v.voteable_id") + .joins("inner join #{self.class.table_name} u on u.id = #{object.name.tableize}.#{self.class.name.foreign_key}") + .length end return karma_value end - - def options_for_karma (object, options = {}) - #GuillaumeNM : 2009-01-30 Adding condition for SQLite3 - conditions = ["u.id = ? AND vote = ?" , self[:id] , true] - joins = ["inner join votes v on #{object.table_name}.id = v.voteable_id", "inner join #{self.class.table_name} u on u.id = #{object.name.tableize}.#{self.class.name.foreign_key}"] - { :joins => joins.join(" "), :conditions => conditions }.update(options) - end - + end - + end end end diff --git a/vendor/plugins/xss_terminate/tasks/xss_terminate_tasks.rake b/vendor/plugins/xss_terminate/tasks/xss_terminate_tasks.rake index d9c4571..b021e2b 100644 --- a/vendor/plugins/xss_terminate/tasks/xss_terminate_tasks.rake +++ b/vendor/plugins/xss_terminate/tasks/xss_terminate_tasks.rake @@ -2,6 +2,6 @@ desc "Given MODELS=Foo,Bar,Baz find all instances in the DB and save to sanitize task :xss_terminate => :environment do models = ENV['MODELS'].split(',') models.each do |model| - model.constantize.find(:all).map(&:save) + model.constantize.all.map(&:save) end end -- libgit2 0.21.2