Commit 1676500ee81f8b768de2e9fa766ce7a00d089369

Authored by Braulio Bhavamitra
1 parent a7561344

Use ApplicationRecord pattern

Anticipating a pattern from Rails 5
Showing 167 changed files with 310 additions and 353 deletions   Show diff stats
README.rails.md
@@ -99,7 +99,7 @@ Description of contents @@ -99,7 +99,7 @@ Description of contents
99 Holds controllers that should be named like weblog_controller.rb for automated URL mapping. All controllers should descend from `ActionController::Base`. 99 Holds controllers that should be named like weblog_controller.rb for automated URL mapping. All controllers should descend from `ActionController::Base`.
100 100
101 * `app/models` 101 * `app/models`
102 - Holds models that should be named like post.rb. Most models will descend from `ActiveRecord::Base`. 102 + Holds models that should be named like post.rb. Most models will descend from `ApplicationRecord`.
103 103
104 * `app/views` 104 * `app/views`
105 Holds the template files for the view that should be named like `weblog/index.rhtml` for the `WeblogController#index` action. All views use eRuby syntax. This directory can also be used to keep stylesheets, images, and so on that can be symlinked to public. 105 Holds the template files for the view that should be named like `weblog/index.rhtml` for the `WeblogController#index` action. All views use eRuby syntax. This directory can also be used to keep stylesheets, images, and so on that can be symlinked to public.
app/mailers/mailing.rb
1 require_dependency 'mailing_job' 1 require_dependency 'mailing_job'
2 2
3 -class Mailing < ActiveRecord::Base 3 +class Mailing < ApplicationRecord
4 4
5 acts_as_having_settings :field => :data 5 acts_as_having_settings :field => :data
6 6
app/models/abuse_report.rb
1 -class AbuseReport < ActiveRecord::Base 1 +class AbuseReport < ApplicationRecord
2 2
3 attr_accessible :content, :reason 3 attr_accessible :content, :reason
4 4
app/models/action_tracker_notification.rb
1 -class ActionTrackerNotification < ActiveRecord::Base 1 +class ActionTrackerNotification < ApplicationRecord
2 2
3 belongs_to :profile 3 belongs_to :profile
4 belongs_to :action_tracker, :class_name => 'ActionTracker::Record', :foreign_key => 'action_tracker_id' 4 belongs_to :action_tracker, :class_name => 'ActionTracker::Record', :foreign_key => 'action_tracker_id'
app/models/application_record.rb 0 → 100644
@@ -0,0 +1,64 @@ @@ -0,0 +1,64 @@
  1 +class ApplicationRecord < ActiveRecord::Base
  2 +
  3 + self.abstract_class = true
  4 +
  5 + def self.postgresql?
  6 + self.connection.adapter_name == 'PostgreSQL'
  7 + end
  8 +
  9 + # an ActionView instance for rendering views on models
  10 + def self.action_view
  11 + @action_view ||= begin
  12 + view_paths = ::ActionController::Base.view_paths
  13 + action_view = ::ActionView::Base.new view_paths
  14 + # for using Noosfero helpers inside render calls
  15 + action_view.extend ::ApplicationHelper
  16 + action_view
  17 + end
  18 + end
  19 +
  20 + # default value needed for the above ActionView
  21 + def to_partial_path
  22 + self.class.name.underscore
  23 + end
  24 +
  25 + alias :meta_cache_key :cache_key
  26 + def cache_key
  27 + key = [Noosfero::VERSION, meta_cache_key]
  28 + key.unshift(ApplicationRecord.connection.schema_search_path) if ApplicationRecord.postgresql?
  29 + key.join('/')
  30 + end
  31 +
  32 + def self.like_search(query, options={})
  33 + if defined?(self::SEARCHABLE_FIELDS) || options[:fields].present?
  34 + fields_per_table = {}
  35 + fields_per_table[table_name] = (options[:fields].present? ? options[:fields] : self::SEARCHABLE_FIELDS.keys.map(&:to_s)) & column_names
  36 +
  37 + if options[:joins].present?
  38 + join_asset = options[:joins].to_s.classify.constantize
  39 + if defined?(join_asset::SEARCHABLE_FIELDS) || options[:fields].present?
  40 + fields_per_table[join_asset.table_name] = (options[:fields].present? ? options[:fields] : join_asset::SEARCHABLE_FIELDS.keys.map(&:to_s)) & join_asset.column_names
  41 + end
  42 + end
  43 +
  44 + query = query.downcase.strip
  45 + fields_per_table.delete_if { |table,fields| fields.blank? }
  46 + conditions = fields_per_table.map do |table,fields|
  47 + fields.map do |field|
  48 + "lower(#{table}.#{field}) LIKE '%#{query}%'"
  49 + end.join(' OR ')
  50 + end.join(' OR ')
  51 +
  52 + if options[:joins].present?
  53 + joins(options[:joins]).where(conditions)
  54 + else
  55 + where(conditions)
  56 + end
  57 +
  58 + else
  59 + raise "No searchable fields defined for #{self.name}"
  60 + end
  61 + end
  62 +
  63 +end
  64 +
app/models/article.rb
1 1
2 -class Article < ActiveRecord::Base 2 +class Article < ApplicationRecord
3 3
4 include SanitizeHelper 4 include SanitizeHelper
5 5
app/models/article_categorization.rb
1 -class ArticleCategorization < ActiveRecord::Base 1 +class ArticleCategorization < ApplicationRecord
2 self.table_name = :articles_categories 2 self.table_name = :articles_categories
3 3
4 belongs_to :article 4 belongs_to :article
app/models/article_follower.rb
1 -class ArticleFollower < ActiveRecord::Base 1 +class ArticleFollower < ApplicationRecord
2 2
3 attr_accessible :article_id, :person_id 3 attr_accessible :article_id, :person_id
4 belongs_to :article, :counter_cache => :followers_count 4 belongs_to :article, :counter_cache => :followers_count
app/models/block.rb
1 -class Block < ActiveRecord::Base 1 +class Block < ApplicationRecord
2 2
3 attr_accessible :title, :subtitle, :display, :limit, :box_id, :posts_per_page, 3 attr_accessible :title, :subtitle, :display, :limit, :box_id, :posts_per_page,
4 :visualization_format, :language, :display_user, 4 :visualization_format, :language, :display_user,
app/models/box.rb
1 -class Box < ActiveRecord::Base 1 +class Box < ApplicationRecord
2 2
3 acts_as_list scope: -> box { where owner_id: box.owner_id, owner_type: box.owner_type } 3 acts_as_list scope: -> box { where owner_id: box.owner_id, owner_type: box.owner_type }
4 4
app/models/category.rb
1 -class Category < ActiveRecord::Base 1 +class Category < ApplicationRecord
2 2
3 attr_accessible :name, :parent_id, :display_color, :display_in_menu, :image_builder, :environment, :parent 3 attr_accessible :name, :parent_id, :display_color, :display_in_menu, :image_builder, :environment, :parent
4 4
app/models/certifier.rb
1 -class Certifier < ActiveRecord::Base 1 +class Certifier < ApplicationRecord
2 2
3 attr_accessible :name, :environment 3 attr_accessible :name, :environment
4 4
app/models/chat_message.rb
1 -class ChatMessage < ActiveRecord::Base 1 +class ChatMessage < ApplicationRecord
  2 +
2 attr_accessible :body, :from, :to 3 attr_accessible :body, :from, :to
3 4
4 belongs_to :to, :class_name => 'Profile' 5 belongs_to :to, :class_name => 'Profile'
app/models/comment.rb
1 -class Comment < ActiveRecord::Base 1 +class Comment < ApplicationRecord
2 2
3 SEARCHABLE_FIELDS = { 3 SEARCHABLE_FIELDS = {
4 :title => {:label => _('Title'), :weight => 10}, 4 :title => {:label => _('Title'), :weight => 10},
app/models/contact_list.rb
1 -class ContactList < ActiveRecord::Base 1 +class ContactList < ApplicationRecord
2 2
3 serialize :list, Array 3 serialize :list, Array
4 4
app/models/custom_field.rb
1 -class CustomField < ActiveRecord::Base 1 +class CustomField < ApplicationRecord
  2 +
2 attr_accessible :name, :default_value, :format, :extras, :customized_type, :active, :required, :signup, :environment, :moderation_task 3 attr_accessible :name, :default_value, :format, :extras, :customized_type, :active, :required, :signup, :environment, :moderation_task
3 serialize :customized_type 4 serialize :customized_type
4 serialize :extras 5 serialize :extras
app/models/custom_field_value.rb
1 -class CustomFieldValue < ActiveRecord::Base 1 +class CustomFieldValue < ApplicationRecord
  2 +
2 belongs_to :custom_field 3 belongs_to :custom_field
3 belongs_to :customized, :polymorphic => true 4 belongs_to :customized, :polymorphic => true
4 attr_accessible :value, :public, :customized, :custom_field, :customized_type 5 attr_accessible :value, :public, :customized, :custom_field, :customized_type
app/models/domain.rb
1 require 'noosfero/multi_tenancy' 1 require 'noosfero/multi_tenancy'
2 2
3 -class Domain < ActiveRecord::Base 3 +class Domain < ApplicationRecord
4 4
5 attr_accessible :name, :owner, :is_default 5 attr_accessible :name, :owner, :is_default
6 6
app/models/email_template.rb
1 -class EmailTemplate < ActiveRecord::Base 1 +class EmailTemplate < ApplicationRecord
2 2
3 belongs_to :owner, :polymorphic => true 3 belongs_to :owner, :polymorphic => true
4 4
app/models/environment.rb
1 # A Environment is like a website to be hosted in the platform. It may 1 # A Environment is like a website to be hosted in the platform. It may
2 # contain multiple Profile's and can be identified by several different 2 # contain multiple Profile's and can be identified by several different
3 # domains. 3 # domains.
4 -class Environment < ActiveRecord::Base 4 +class Environment < ApplicationRecord
5 5
6 attr_accessible :name, :is_default, :signup_welcome_text_subject, 6 attr_accessible :name, :is_default, :signup_welcome_text_subject,
7 :signup_welcome_text_body, :terms_of_use, 7 :signup_welcome_text_body, :terms_of_use,
app/models/external_feed.rb
1 -class ExternalFeed < ActiveRecord::Base 1 +class ExternalFeed < ApplicationRecord
2 2
3 belongs_to :blog 3 belongs_to :blog
4 validates_presence_of :blog_id 4 validates_presence_of :blog_id
app/models/favorite_enterprise_person.rb
1 -class FavoriteEnterprisePerson < ActiveRecord::Base 1 +class FavoriteEnterprisePerson < ApplicationRecord
2 2
3 attr_accessible :person, :enterprise 3 attr_accessible :person, :enterprise
4 4
app/models/friendship.rb
1 -class Friendship < ActiveRecord::Base 1 +class Friendship < ApplicationRecord
2 track_actions :new_friendship, :after_create, :keep_params => ["friend.name", "friend.url", "friend.profile_custom_icon"], :custom_user => :person 2 track_actions :new_friendship, :after_create, :keep_params => ["friend.name", "friend.url", "friend.profile_custom_icon"], :custom_user => :person
3 3
4 extend CacheCounterHelper 4 extend CacheCounterHelper
app/models/image.rb
1 -class Image < ActiveRecord::Base 1 +class Image < ApplicationRecord
2 2
3 attr_accessible :uploaded_data, :label, :remove_image 3 attr_accessible :uploaded_data, :label, :remove_image
4 attr_accessor :remove_image 4 attr_accessor :remove_image
app/models/input.rb
1 -class Input < ActiveRecord::Base 1 +class Input < ApplicationRecord
2 2
3 attr_accessible :product, :product_id, :product_category, :product_category_id, 3 attr_accessible :product, :product_id, :product_category, :product_category_id,
4 :amount_used, :unit_id, :price_per_unit, :relevant_to_price, :is_from_solidarity_economy 4 :amount_used, :unit_id, :price_per_unit, :relevant_to_price, :is_from_solidarity_economy
app/models/license.rb
1 -class License < ActiveRecord::Base 1 +class License < ApplicationRecord
2 2
3 attr_accessible :name, :url 3 attr_accessible :name, :url
4 4
app/models/mailing_sent.rb
1 -class MailingSent < ActiveRecord::Base 1 +class MailingSent < ApplicationRecord
  2 +
2 attr_accessible :person 3 attr_accessible :person
3 belongs_to :mailing 4 belongs_to :mailing
4 belongs_to :person 5 belongs_to :person
app/models/national_region.rb
1 -class NationalRegion < ActiveRecord::Base 1 +class NationalRegion < ApplicationRecord
2 2
3 SEARCHABLE_FIELDS = { 3 SEARCHABLE_FIELDS = {
4 :name => {:label => _('Name'), :weight => 1}, 4 :name => {:label => _('Name'), :weight => 1},
app/models/national_region_type.rb
1 -class NationalRegionType < ActiveRecord::Base 1 +class NationalRegionType < ApplicationRecord
2 COUNTRY = 1 2 COUNTRY = 1
3 STATE = 2 3 STATE = 2
4 CITY = 3 4 CITY = 3
app/models/person.rb
@@ -336,7 +336,7 @@ class Person &lt; Profile @@ -336,7 +336,7 @@ class Person &lt; Profile
336 environment ||= self.environment 336 environment ||= self.environment
337 role_assignments.includes([:role, :resource]).select { |ra| ra.resource == environment }.map{|ra|ra.role.permissions}.any? do |ps| 337 role_assignments.includes([:role, :resource]).select { |ra| ra.resource == environment }.map{|ra|ra.role.permissions}.any? do |ps|
338 ps.any? do |p| 338 ps.any? do |p|
339 - ActiveRecord::Base::PERMISSIONS['Environment'].keys.include?(p) 339 + ApplicationRecord::PERMISSIONS['Environment'].keys.include?(p)
340 end 340 end
341 end 341 end
342 end 342 end
app/models/price_detail.rb
1 -class PriceDetail < ActiveRecord::Base 1 +class PriceDetail < ApplicationRecord
2 2
3 attr_accessible :price, :production_cost_id 3 attr_accessible :price, :production_cost_id
4 4
app/models/product.rb
1 -class Product < ActiveRecord::Base 1 +class Product < ApplicationRecord
2 2
3 SEARCHABLE_FIELDS = { 3 SEARCHABLE_FIELDS = {
4 :name => {:label => _('Name'), :weight => 10}, 4 :name => {:label => _('Name'), :weight => 10},
app/models/product_qualifier.rb
1 -class ProductQualifier < ActiveRecord::Base 1 +class ProductQualifier < ApplicationRecord
2 2
3 attr_accessible :qualifier, :product, :certifier 3 attr_accessible :qualifier, :product, :certifier
4 4
app/models/production_cost.rb
1 -class ProductionCost < ActiveRecord::Base 1 +class ProductionCost < ApplicationRecord
2 2
3 attr_accessible :name, :owner 3 attr_accessible :name, :owner
4 4
app/models/profile.rb
1 # A Profile is the representation and web-presence of an individual or an 1 # A Profile is the representation and web-presence of an individual or an
2 # organization. Every Profile is attached to its Environment of origin, 2 # organization. Every Profile is attached to its Environment of origin,
3 # which by default is the one returned by Environment:default. 3 # which by default is the one returned by Environment:default.
4 -class Profile < ActiveRecord::Base 4 +class Profile < ApplicationRecord
5 5
6 attr_accessible :name, :identifier, :public_profile, :nickname, :custom_footer, :custom_header, :address, :zip_code, :contact_phone, :image_builder, :description, :closed, :template_id, :environment, :lat, :lng, :is_template, :fields_privacy, :preferred_domain_id, :category_ids, :country, :city, :state, :national_region_code, :email, :contact_email, :redirect_l10n, :notification_time, 6 attr_accessible :name, :identifier, :public_profile, :nickname, :custom_footer, :custom_header, :address, :zip_code, :contact_phone, :image_builder, :description, :closed, :template_id, :environment, :lat, :lng, :is_template, :fields_privacy, :preferred_domain_id, :category_ids, :country, :city, :state, :national_region_code, :email, :contact_email, :redirect_l10n, :notification_time,
7 :redirection_after_login, :custom_url_redirection, 7 :redirection_after_login, :custom_url_redirection,
app/models/profile_activity.rb
1 -class ProfileActivity < ActiveRecord::Base 1 +class ProfileActivity < ApplicationRecord
2 2
3 self.record_timestamps = false 3 self.record_timestamps = false
4 4
app/models/profile_categorization.rb
1 -class ProfileCategorization < ActiveRecord::Base 1 +class ProfileCategorization < ApplicationRecord
2 self.table_name = :categories_profiles 2 self.table_name = :categories_profiles
3 belongs_to :profile 3 belongs_to :profile
4 belongs_to :category 4 belongs_to :category
app/models/profile_suggestion.rb
1 -class ProfileSuggestion < ActiveRecord::Base 1 +class ProfileSuggestion < ApplicationRecord
  2 +
2 belongs_to :person 3 belongs_to :person
3 belongs_to :suggestion, :class_name => 'Profile', :foreign_key => :suggestion_id 4 belongs_to :suggestion, :class_name => 'Profile', :foreign_key => :suggestion_id
4 5
app/models/qualifier.rb
1 -class Qualifier < ActiveRecord::Base 1 +class Qualifier < ApplicationRecord
2 2
3 attr_accessible :name, :environment 3 attr_accessible :name, :environment
4 4
app/models/qualifier_certifier.rb
1 -class QualifierCertifier < ActiveRecord::Base 1 +class QualifierCertifier < ApplicationRecord
2 belongs_to :qualifier 2 belongs_to :qualifier
3 belongs_to :certifier 3 belongs_to :certifier
4 4
app/models/reported_image.rb
1 -class ReportedImage < ActiveRecord::Base 1 +class ReportedImage < ApplicationRecord
2 belongs_to :abuse_report 2 belongs_to :abuse_report
3 3
4 validates_presence_of :abuse_report 4 validates_presence_of :abuse_report
app/models/scrap.rb
1 -class Scrap < ActiveRecord::Base 1 +class Scrap < ApplicationRecord
2 2
3 include SanitizeHelper 3 include SanitizeHelper
4 4
app/models/search_term.rb
1 -class SearchTerm < ActiveRecord::Base 1 +class SearchTerm < ApplicationRecord
2 validates_presence_of :term, :context 2 validates_presence_of :term, :context
3 validates_uniqueness_of :term, :scope => [:context_id, :context_type, :asset] 3 validates_uniqueness_of :term, :scope => [:context_id, :context_type, :asset]
4 4
@@ -25,7 +25,7 @@ class SearchTerm &lt; ActiveRecord::Base @@ -25,7 +25,7 @@ class SearchTerm &lt; ActiveRecord::Base
25 # Therefore the score is 97. Them we sum every score to get the total score 25 # Therefore the score is 97. Them we sum every score to get the total score
26 # for a search term. 26 # for a search term.
27 def self.occurrences_scores 27 def self.occurrences_scores
28 - Hash[*ActiveRecord::Base.connection.execute( 28 + Hash[*ApplicationRecord.connection.execute(
29 joins(:occurrences). 29 joins(:occurrences).
30 select("search_terms.id, sum(#{SearchTermOccurrence::EXPIRATION_TIME.to_i} - extract(epoch from (now() - search_term_occurrences.created_at))) as value"). 30 select("search_terms.id, sum(#{SearchTermOccurrence::EXPIRATION_TIME.to_i} - extract(epoch from (now() - search_term_occurrences.created_at))) as value").
31 where("search_term_occurrences.created_at > ?", DateTime.now - SearchTermOccurrence::EXPIRATION_TIME). 31 where("search_term_occurrences.created_at > ?", DateTime.now - SearchTermOccurrence::EXPIRATION_TIME).
app/models/search_term_occurrence.rb
1 -class SearchTermOccurrence < ActiveRecord::Base 1 +class SearchTermOccurrence < ApplicationRecord
2 2
3 belongs_to :search_term 3 belongs_to :search_term
4 validates_presence_of :search_term 4 validates_presence_of :search_term
app/models/suggestion_connection.rb
1 -class SuggestionConnection < ActiveRecord::Base 1 +class SuggestionConnection < ApplicationRecord
  2 +
2 attr_accessible :suggestion, :suggestion_id, :connection_type, :connection_id 3 attr_accessible :suggestion, :suggestion_id, :connection_type, :connection_id
3 4
4 belongs_to :suggestion, :class_name => 'ProfileSuggestion', :foreign_key => 'suggestion_id' 5 belongs_to :suggestion, :class_name => 'ProfileSuggestion', :foreign_key => 'suggestion_id'
app/models/task.rb
@@ -9,7 +9,7 @@ @@ -9,7 +9,7 @@
9 # This class has a +data+ field of type <tt>text</tt>, where you can store any 9 # This class has a +data+ field of type <tt>text</tt>, where you can store any
10 # type of data (as serialized Ruby objects) you need for your subclass (which 10 # type of data (as serialized Ruby objects) you need for your subclass (which
11 # will need to declare <ttserialize</tt> itself). 11 # will need to declare <ttserialize</tt> itself).
12 -class Task < ActiveRecord::Base 12 +class Task < ApplicationRecord
13 13
14 acts_as_having_settings :field => :data 14 acts_as_having_settings :field => :data
15 15
app/models/thumbnail.rb
1 -class Thumbnail < ActiveRecord::Base 1 +class Thumbnail < ApplicationRecord
2 2
3 attr_accessible :uploaded_data 3 attr_accessible :uploaded_data
4 # mass assigned by attachment_fu 4 # mass assigned by attachment_fu
app/models/unit.rb
1 -class Unit < ActiveRecord::Base 1 +class Unit < ApplicationRecord
2 2
3 acts_as_list scope: -> unit { where environment_id: unit.environment_id } 3 acts_as_list scope: -> unit { where environment_id: unit.environment_id }
4 4
app/models/user.rb
@@ -4,7 +4,7 @@ require &#39;securerandom&#39; @@ -4,7 +4,7 @@ require &#39;securerandom&#39;
4 4
5 # User models the system users, and is generated by the acts_as_authenticated 5 # User models the system users, and is generated by the acts_as_authenticated
6 # Rails generator. 6 # Rails generator.
7 -class User < ActiveRecord::Base 7 +class User < ApplicationRecord
8 8
9 attr_accessible :login, :email, :password, :password_confirmation, :activated_at 9 attr_accessible :login, :email, :password, :password_confirmation, :activated_at
10 10
app/models/validation_info.rb
1 -class ValidationInfo < ActiveRecord::Base 1 +class ValidationInfo < ApplicationRecord
2 2
3 attr_accessible :validation_methodology, :restrictions, :organization 3 attr_accessible :validation_methodology, :restrictions, :organization
4 4
app/views/profile_roles/_form.html.erb
@@ -9,7 +9,7 @@ @@ -9,7 +9,7 @@
9 <% permissions.each do |key| %> 9 <% permissions.each do |key| %>
10 <div class="permissions <%= key.downcase %>"> 10 <div class="permissions <%= key.downcase %>">
11 <h4><%= _('%s Permissions:' % key) %></h4> 11 <h4><%= _('%s Permissions:' % key) %></h4>
12 - <% ActiveRecord::Base::PERMISSIONS[key].keys.each do |p| %> 12 + <% ApplicationRecord::PERMISSIONS[key].keys.each do |p| %>
13 <%= check_box_tag("role[permissions][]", p, role.has_permission?(p), { :id => p }) %> 13 <%= check_box_tag("role[permissions][]", p, role.has_permission?(p), { :id => p }) %>
14 <%= content_tag(:label, permission_name(p), { :for => p }) %><br/> 14 <%= content_tag(:label, permission_name(p), { :for => p }) %><br/>
15 <% end %> 15 <% end %>
app/views/role/_form.html.erb
@@ -9,7 +9,7 @@ @@ -9,7 +9,7 @@
9 <% permissions.each do |key| %> 9 <% permissions.each do |key| %>
10 <div class="permissions <%= key.downcase %>"> 10 <div class="permissions <%= key.downcase %>">
11 <h4><%= _('%s Permissions:' % key) %></h4> 11 <h4><%= _('%s Permissions:' % key) %></h4>
12 - <% ActiveRecord::Base::PERMISSIONS[key].keys.each do |p| %> 12 + <% ApplicationRecord::PERMISSIONS[key].keys.each do |p| %>
13 <%= check_box_tag("role[permissions][]", p, role.has_permission?(p), { :id => p }) %> 13 <%= check_box_tag("role[permissions][]", p, role.has_permission?(p), { :id => p }) %>
14 <%= content_tag(:label, permission_name(p), { :for => p }) %><br/> 14 <%= content_tag(:label, permission_name(p), { :for => p }) %><br/>
15 <% end %> 15 <% end %>
config/initializers/active_record_extensions.rb
@@ -14,4 +14,5 @@ module ActiveRecordExtension @@ -14,4 +14,5 @@ module ActiveRecordExtension
14 end 14 end
15 end 15 end
16 end 16 end
17 -ActiveRecord::Base.send(:include, ActiveRecordExtension) 17 +
  18 +ApplicationRecord.send :include, ActiveRecordExtension
db/migrate/033_destroy_organization_and_person_infos.rb
1 class DestroyOrganizationAndPersonInfos < ActiveRecord::Migration 1 class DestroyOrganizationAndPersonInfos < ActiveRecord::Migration
2 def self.up 2 def self.up
3 Person.find_each do |i| 3 Person.find_each do |i|
4 - info = ActiveRecord::Base.connection.select_one("select * from person_infos where person_id = #{i.id}") 4 + info = ApplicationRecord.connection.select_one("select * from person_infos where person_id = #{i.id}")
5 i.name = info["name"] unless info["name"].nil? 5 i.name = info["name"] unless info["name"].nil?
6 i.address = info["address"] unless info["address"].nil? 6 i.address = info["address"] unless info["address"].nil?
7 [ "photo", "contact_information", "birth_date", "sex", "city", "state", "country" ].each do |field| 7 [ "photo", "contact_information", "birth_date", "sex", "city", "state", "country" ].each do |field|
@@ -12,7 +12,7 @@ class DestroyOrganizationAndPersonInfos &lt; ActiveRecord::Migration @@ -12,7 +12,7 @@ class DestroyOrganizationAndPersonInfos &lt; ActiveRecord::Migration
12 drop_table :person_infos 12 drop_table :person_infos
13 13
14 Organization.find_each do |i| 14 Organization.find_each do |i|
15 - info = ActiveRecord::Base.connection.select_one("select * from organization_infos where organization_id = #{i.id}") 15 + info = ApplicationRecord.connection.select_one("select * from organization_infos where organization_id = #{i.id}")
16 [ "contact_person", "contact_email", "acronym", "foundation_year", "legal_form", "economic_activity", "management_information", "validated" ].each do |field| 16 [ "contact_person", "contact_email", "acronym", "foundation_year", "legal_form", "economic_activity", "management_information", "validated" ].each do |field|
17 i.send("#{field}=", info[field]) 17 i.send("#{field}=", info[field])
18 end 18 end
db/migrate/059_add_birth_date_to_person.rb
@@ -29,7 +29,7 @@ class AddBirthDateToPerson &lt; ActiveRecord::Migration @@ -29,7 +29,7 @@ class AddBirthDateToPerson &lt; ActiveRecord::Migration
29 end 29 end
30 end 30 end
31 31
32 - class Person < ActiveRecord::Base 32 + class Person < ApplicationRecord
33 self.table_name = 'profiles' 33 self.table_name = 'profiles'
34 serialize :data, Hash 34 serialize :data, Hash
35 end 35 end
db/migrate/069_add_enviroment_id_to_role.rb
1 -class Role < ActiveRecord::Base; end  
2 -class RoleWithEnvironment < ActiveRecord::Base 1 +class Role < ApplicationRecord
  2 +class RoleWithEnvironment < ApplicationRecord
3 self.table_name = 'roles' 3 self.table_name = 'roles'
4 belongs_to :environment 4 belongs_to :environment
5 end 5 end
6 -class RoleAssignment < ActiveRecord::Base 6 +class RoleAssignment < ApplicationRecord
7 belongs_to :accessor, :polymorphic => true 7 belongs_to :accessor, :polymorphic => true
8 belongs_to :resource, :polymorphic => true 8 belongs_to :resource, :polymorphic => true
9 end 9 end
db/migrate/074_move_title_to_name_from_blogs.rb
@@ -2,7 +2,7 @@ class MoveTitleToNameFromBlogs &lt; ActiveRecord::Migration @@ -2,7 +2,7 @@ class MoveTitleToNameFromBlogs &lt; ActiveRecord::Migration
2 def self.up 2 def self.up
3 select_all("select id, setting from articles where type = 'Blog' and name != 'Blog'").each do |blog| 3 select_all("select id, setting from articles where type = 'Blog' and name != 'Blog'").each do |blog|
4 title = YAML.load(blog['setting'])[:title] 4 title = YAML.load(blog['setting'])[:title]
5 - assignments = ActiveRecord::Base.sanitize_sql_for_assignment(:name => title) 5 + assignments = ApplicationRecord.sanitize_sql_for_assignment(:name => title)
6 update("update articles set %s where id = %d" % [assignments, blog['id']] ) 6 update("update articles set %s where id = %d" % [assignments, blog['id']] )
7 end 7 end
8 end 8 end
db/migrate/20100921121528_add_is_image_to_articles.rb
@@ -3,7 +3,7 @@ class AddIsImageToArticles &lt; ActiveRecord::Migration @@ -3,7 +3,7 @@ class AddIsImageToArticles &lt; ActiveRecord::Migration
3 add_column :articles, :is_image, :boolean, :default => false 3 add_column :articles, :is_image, :boolean, :default => false
4 add_column :article_versions, :is_image, :boolean, :default => false 4 add_column :article_versions, :is_image, :boolean, :default => false
5 5
6 - execute ActiveRecord::Base.sanitize_sql(["update articles set is_image = ? where articles.content_type like 'image/%'", true]) 6 + execute ApplicationRecord.sanitize_sql(["update articles set is_image = ? where articles.content_type like 'image/%'", true])
7 end 7 end
8 8
9 def self.down 9 def self.down
db/migrate/20101129234429_convert_folders_to_galleries.rb
@@ -10,7 +10,7 @@ class ConvertFoldersToGalleries &lt; ActiveRecord::Migration @@ -10,7 +10,7 @@ class ConvertFoldersToGalleries &lt; ActiveRecord::Migration
10 select_all("select id, setting from articles where type = 'Gallery'").each do |folder| 10 select_all("select id, setting from articles where type = 'Gallery'").each do |folder|
11 settings = YAML.load(folder['setting'] || {}.to_yaml) 11 settings = YAML.load(folder['setting'] || {}.to_yaml)
12 settings[:view_as] = 'image_gallery' 12 settings[:view_as] = 'image_gallery'
13 - assignments = ActiveRecord::Base.sanitize_sql_for_assignment(:setting => settings.to_yaml) 13 + assignments = ApplicationRecord.sanitize_sql_for_assignment(:setting => settings.to_yaml)
14 update("update articles set %s, type = 'Folder' where id = %d" % [assignments, folder['id']]) 14 update("update articles set %s, type = 'Folder' where id = %d" % [assignments, folder['id']])
15 end 15 end
16 end 16 end
db/migrate/20101202205446_remove_published_articles.rb
@@ -3,7 +3,7 @@ class RemovePublishedArticles &lt; ActiveRecord::Migration @@ -3,7 +3,7 @@ class RemovePublishedArticles &lt; ActiveRecord::Migration
3 select_all("SELECT * from articles WHERE type = 'PublishedArticle'").each do |published| 3 select_all("SELECT * from articles WHERE type = 'PublishedArticle'").each do |published|
4 reference = select_one('select * from articles where id = %d' % published['reference_article_id']) 4 reference = select_one('select * from articles where id = %d' % published['reference_article_id'])
5 if reference 5 if reference
6 - execute(ActiveRecord::Base.sanitize_sql(["UPDATE articles SET type = ?, abstract = ?, body = ? WHERE articles.id = ?", reference['type'], reference['abstract'], reference['body'], published['id']])) 6 + execute(ApplicationRecord.sanitize_sql(["UPDATE articles SET type = ?, abstract = ?, body = ? WHERE articles.id = ?", reference['type'], reference['abstract'], reference['body'], published['id']]))
7 else 7 else
8 execute("DELETE from articles where articles.id = #{published['id']}") 8 execute("DELETE from articles where articles.id = #{published['id']}")
9 end 9 end
db/migrate/20101205034144_add_language_and_translation_of_id_to_article.rb
@@ -11,7 +11,7 @@ class AddLanguageAndTranslationOfIdToArticle &lt; ActiveRecord::Migration @@ -11,7 +11,7 @@ class AddLanguageAndTranslationOfIdToArticle &lt; ActiveRecord::Migration
11 select_all("select id, setting from articles where type = 'Blog'").each do |blog| 11 select_all("select id, setting from articles where type = 'Blog'").each do |blog|
12 settings = YAML.load(blog['setting'] || {}.to_yaml) 12 settings = YAML.load(blog['setting'] || {}.to_yaml)
13 settings[:display_posts_in_current_language] = true 13 settings[:display_posts_in_current_language] = true
14 - assignments = ActiveRecord::Base.sanitize_sql_for_assignment(:setting => settings.to_yaml) 14 + assignments = ApplicationRecord.sanitize_sql_for_assignment(:setting => settings.to_yaml)
15 update("update articles set %s where id = %d" % [assignments, blog['id']]) 15 update("update articles set %s where id = %d" % [assignments, blog['id']])
16 end 16 end
17 17
db/migrate/20110203160153_rename_images_path_on_tracked_actions.rb
@@ -15,7 +15,7 @@ class RenameImagesPathOnTrackedActions &lt; ActiveRecord::Migration @@ -15,7 +15,7 @@ class RenameImagesPathOnTrackedActions &lt; ActiveRecord::Migration
15 end 15 end
16 params[param_name] = paths 16 params[param_name] = paths
17 17
18 - execute(ActiveRecord::Base.sanitize_sql(["UPDATE action_tracker SET params = ? WHERE id = ?", params.to_yaml, tracker['id']])) 18 + execute(ApplicationRecord.sanitize_sql(["UPDATE action_tracker SET params = ? WHERE id = ?", params.to_yaml, tracker['id']]))
19 end 19 end
20 end 20 end
21 21
db/migrate/20110215153624_move_data_serialized_hash_to_setting_field_for_articles.rb
@@ -12,9 +12,9 @@ class MoveDataSerializedHashToSettingFieldForArticles &lt; ActiveRecord::Migration @@ -12,9 +12,9 @@ class MoveDataSerializedHashToSettingFieldForArticles &lt; ActiveRecord::Migration
12 end 12 end
13 if body.kind_of?(Hash) 13 if body.kind_of?(Hash)
14 settings = article.setting.merge(body) 14 settings = article.setting.merge(body)
15 - body = ActiveRecord::Base.sanitize_sql_for_assignment(:body => settings[:description]) 15 + body = ApplicationRecord.sanitize_sql_for_assignment(:body => settings[:description])
16 update("UPDATE articles set %s WHERE id = %d" % [body, article.id]) 16 update("UPDATE articles set %s WHERE id = %d" % [body, article.id])
17 - setting = ActiveRecord::Base.sanitize_sql_for_assignment(:setting => settings.to_yaml) 17 + setting = ApplicationRecord.sanitize_sql_for_assignment(:setting => settings.to_yaml)
18 update("UPDATE articles set %s WHERE id = %d" % [setting, article.id]) 18 update("UPDATE articles set %s WHERE id = %d" % [setting, article.id])
19 end 19 end
20 end 20 end
db/migrate/20110302214607_move_data_serialized_hash_to_setting_field_for_events.rb
@@ -11,9 +11,9 @@ class MoveDataSerializedHashToSettingFieldForEvents &lt; ActiveRecord::Migration @@ -11,9 +11,9 @@ class MoveDataSerializedHashToSettingFieldForEvents &lt; ActiveRecord::Migration
11 end 11 end
12 if body.kind_of?(Hash) 12 if body.kind_of?(Hash)
13 settings = article.setting.merge(body) 13 settings = article.setting.merge(body)
14 - body = ActiveRecord::Base.sanitize_sql_for_assignment(:body => settings[:description]) 14 + body = ApplicationRecord.sanitize_sql_for_assignment(:body => settings[:description])
15 update("UPDATE articles set %s WHERE id = %d" % [body, article.id]) 15 update("UPDATE articles set %s WHERE id = %d" % [body, article.id])
16 - setting = ActiveRecord::Base.sanitize_sql_for_assignment(:setting => settings.to_yaml) 16 + setting = ApplicationRecord.sanitize_sql_for_assignment(:setting => settings.to_yaml)
17 update("UPDATE articles set %s WHERE id = %d" % [setting, article.id]) 17 update("UPDATE articles set %s WHERE id = %d" % [setting, article.id])
18 end 18 end
19 end 19 end
db/migrate/20110706171330_fix_misunderstood_script_filename.rb
@@ -2,7 +2,7 @@ @@ -2,7 +2,7 @@
2 # from the migration fall on a loop and breaks the migration. Both them are 2 # from the migration fall on a loop and breaks the migration. Both them are
3 # related to alias_method_chain, probably there is a problem with this kind of 3 # related to alias_method_chain, probably there is a problem with this kind of
4 # alias on the migration level. 4 # alias on the migration level.
5 -class Article < ActiveRecord::Base 5 +class Article < ApplicationRecord
6 def sanitize_tag_list 6 def sanitize_tag_list
7 end 7 end
8 end 8 end
db/migrate/20110824192153_add_activated_at_to_users.rb
@@ -2,7 +2,7 @@ class AddActivatedAtToUsers &lt; ActiveRecord::Migration @@ -2,7 +2,7 @@ class AddActivatedAtToUsers &lt; ActiveRecord::Migration
2 def self.up 2 def self.up
3 add_column :users, :activation_code, :string, :limit => 40 3 add_column :users, :activation_code, :string, :limit => 40
4 add_column :users, :activated_at, :datetime 4 add_column :users, :activated_at, :datetime
5 - if ActiveRecord::Base.connection.adapter_name == 'SQLite' 5 + if ApplicationRecord.connection.adapter_name == 'SQLite'
6 execute "update users set activated_at = datetime();" 6 execute "update users set activated_at = datetime();"
7 else 7 else
8 execute "update users set activated_at = now();" 8 execute "update users set activated_at = now();"
db/migrate/20140724134601_fix_yaml_encoding.rb
1 class FixYamlEncoding < ActiveRecord::Migration 1 class FixYamlEncoding < ActiveRecord::Migration
2 def self.up 2 def self.up
3 - ActiveRecord::Base.transaction do 3 + ApplicationRecord.transaction do
4 fix_encoding(Environment, 'settings') 4 fix_encoding(Environment, 'settings')
5 fix_encoding(Profile, 'data') 5 fix_encoding(Profile, 'data')
6 fix_encoding(Product, 'data') 6 fix_encoding(Product, 'data')
db/migrate/20150216213259_create_profile_activity.rb
1 class CreateProfileActivity < ActiveRecord::Migration 1 class CreateProfileActivity < ActiveRecord::Migration
2 def up 2 def up
3 - ActiveRecord::Base.transaction do 3 + ApplicationRecord.transaction do
4 create_table :profile_activities do |t| 4 create_table :profile_activities do |t|
5 t.integer :profile_id 5 t.integer :profile_id
6 t.integer :activity_id 6 t.integer :activity_id
lib/activities_counter_cache_job.rb
1 class ActivitiesCounterCacheJob 1 class ActivitiesCounterCacheJob
2 2
3 def perform 3 def perform
4 - person_activities_counts = ActiveRecord::Base.connection.execute("SELECT profiles.id, count(action_tracker.id) as count FROM profiles LEFT OUTER JOIN action_tracker ON profiles.id = action_tracker.user_id WHERE (action_tracker.created_at >= #{ActiveRecord::Base.connection.quote(ActionTracker::Record::RECENT_DELAY.days.ago.to_s(:db))}) AND ( (profiles.type = 'Person' ) ) GROUP BY profiles.id;")  
5 - organization_activities_counts = ActiveRecord::Base.connection.execute("SELECT profiles.id, count(action_tracker.id) as count FROM profiles LEFT OUTER JOIN action_tracker ON profiles.id = action_tracker.target_id WHERE (action_tracker.created_at >= #{ActiveRecord::Base.connection.quote(ActionTracker::Record::RECENT_DELAY.days.ago.to_s(:db))}) AND ( (profiles.type = 'Community' OR profiles.type = 'Enterprise' OR profiles.type = 'Organization' ) ) GROUP BY profiles.id;") 4 + person_activities_counts = ApplicationRecord.connection.execute("SELECT profiles.id, count(action_tracker.id) as count FROM profiles LEFT OUTER JOIN action_tracker ON profiles.id = action_tracker.user_id WHERE (action_tracker.created_at >= #{ApplicationRecord.connection.quote(ActionTracker::Record::RECENT_DELAY.days.ago.to_s(:db))}) AND ( (profiles.type = 'Person' ) ) GROUP BY profiles.id;")
  5 + organization_activities_counts = ApplicationRecord.connection.execute("SELECT profiles.id, count(action_tracker.id) as count FROM profiles LEFT OUTER JOIN action_tracker ON profiles.id = action_tracker.target_id WHERE (action_tracker.created_at >= #{ApplicationRecord.connection.quote(ActionTracker::Record::RECENT_DELAY.days.ago.to_s(:db))}) AND ( (profiles.type = 'Community' OR profiles.type = 'Enterprise' OR profiles.type = 'Organization' ) ) GROUP BY profiles.id;")
6 activities_counts = person_activities_counts.entries + organization_activities_counts.entries 6 activities_counts = person_activities_counts.entries + organization_activities_counts.entries
7 activities_counts.each do |count| 7 activities_counts.each do |count|
8 - update_sql = ActiveRecord::Base.__send__(:sanitize_sql, ["UPDATE profiles SET activities_count=? WHERE profiles.id=?;", count['count'].to_i, count['id'] ], '')  
9 - ActiveRecord::Base.connection.execute(update_sql) 8 + update_sql = ApplicationRecord.__send__(:sanitize_sql, ["UPDATE profiles SET activities_count=? WHERE profiles.id=?;", count['count'].to_i, count['id'] ], '')
  9 + ApplicationRecord.connection.execute(update_sql)
10 end 10 end
11 Delayed::Job.enqueue(ActivitiesCounterCacheJob.new, {:priority => -3, :run_at => 1.day.from_now}) 11 Delayed::Job.enqueue(ActivitiesCounterCacheJob.new, {:priority => -3, :run_at => 1.day.from_now})
12 end 12 end
lib/acts_as_customizable.rb
@@ -122,4 +122,4 @@ module Customizable @@ -122,4 +122,4 @@ module Customizable
122 end 122 end
123 end 123 end
124 124
125 -ActiveRecord::Base.send(:include, Customizable) 125 +ApplicationRecord.send :include, Customizable
lib/acts_as_filesystem.rb
@@ -33,7 +33,7 @@ module ActsAsFileSystem @@ -33,7 +33,7 @@ module ActsAsFileSystem
33 module ClassMethods 33 module ClassMethods
34 34
35 def build_ancestry(parent_id = nil, ancestry = '') 35 def build_ancestry(parent_id = nil, ancestry = '')
36 - ActiveRecord::Base.transaction do 36 + ApplicationRecord.transaction do
37 self.base_class.where(parent_id: parent_id).each do |node| 37 self.base_class.where(parent_id: parent_id).each do |node|
38 node.update_column :ancestry, ancestry 38 node.update_column :ancestry, ancestry
39 39
@@ -263,5 +263,5 @@ module ActsAsFileSystem @@ -263,5 +263,5 @@ module ActsAsFileSystem
263 end 263 end
264 end 264 end
265 265
266 -ActiveRecord::Base.extend ActsAsFileSystem::ActsMethods 266 +ApplicationRecord.extend ActsAsFileSystem::ActsMethods
267 267
lib/acts_as_having_boxes.rb
@@ -35,4 +35,4 @@ module ActsAsHavingBoxes @@ -35,4 +35,4 @@ module ActsAsHavingBoxes
35 35
36 end 36 end
37 37
38 -ActiveRecord::Base.extend(ActsAsHavingBoxes::ClassMethods) 38 +ApplicationRecord.extend ActsAsHavingBoxes::ClassMethods
lib/acts_as_having_image.rb
@@ -23,4 +23,5 @@ module ActsAsHavingImage @@ -23,4 +23,5 @@ module ActsAsHavingImage
23 23
24 end 24 end
25 25
26 -ActiveRecord::Base.extend(ActsAsHavingImage::ClassMethods) 26 +ApplicationRecord.extend ActsAsHavingImage::ClassMethods
  27 +
lib/acts_as_having_posts.rb
@@ -47,4 +47,5 @@ module ActsAsHavingPosts @@ -47,4 +47,5 @@ module ActsAsHavingPosts
47 47
48 end 48 end
49 49
50 -ActiveRecord::Base.extend(ActsAsHavingPosts::ClassMethods) 50 +ApplicationRecord.extend ActsAsHavingPosts::ClassMethods
  51 +
lib/acts_as_having_settings.rb
@@ -87,4 +87,5 @@ module ActsAsHavingSettings @@ -87,4 +87,5 @@ module ActsAsHavingSettings
87 87
88 end 88 end
89 89
90 -ActiveRecord::Base.send(:extend, ActsAsHavingSettings::ClassMethods) 90 +ApplicationRecord.extend ActsAsHavingSettings::ClassMethods
  91 +
lib/code_numbering.rb
@@ -55,4 +55,4 @@ module CodeNumbering @@ -55,4 +55,4 @@ module CodeNumbering
55 end 55 end
56 end 56 end
57 57
58 -ActiveRecord::Base.extend CodeNumbering::ClassMethods 58 +ApplicationRecord.extend CodeNumbering::ClassMethods
lib/delayed_attachment_fu.rb
@@ -52,4 +52,5 @@ module DelayedAttachmentFu @@ -52,4 +52,5 @@ module DelayedAttachmentFu
52 end 52 end
53 end 53 end
54 54
55 -ActiveRecord::Base.send(:extend, DelayedAttachmentFu::ClassMethods) 55 +ApplicationRecord.extend DelayedAttachmentFu::ClassMethods
  56 +
lib/noosfero/core_ext.rb
1 require 'noosfero/core_ext/string' 1 require 'noosfero/core_ext/string'
2 require 'noosfero/core_ext/integer' 2 require 'noosfero/core_ext/integer'
3 -require 'noosfero/core_ext/active_record' 3 +require 'noosfero/core_ext/active_record/calculations'
4 require 'noosfero/core_ext/active_record/reflection' 4 require 'noosfero/core_ext/active_record/reflection'
5 5
lib/noosfero/core_ext/active_record.rb
@@ -1,74 +0,0 @@ @@ -1,74 +0,0 @@
1 -require 'active_record'  
2 -  
3 -class ActiveRecord::Base  
4 -  
5 - def self.postgresql?  
6 - ActiveRecord::Base.connection.adapter_name == 'PostgreSQL'  
7 - end  
8 -  
9 - # an ActionView instance for rendering views on models  
10 - def self.action_view  
11 - @action_view ||= begin  
12 - view_paths = ::ActionController::Base.view_paths  
13 - action_view = ::ActionView::Base.new view_paths  
14 - # for using Noosfero helpers inside render calls  
15 - action_view.extend ::ApplicationHelper  
16 - action_view  
17 - end  
18 - end  
19 -  
20 - # default value needed for the above ActionView  
21 - def to_partial_path  
22 - self.class.name.underscore  
23 - end  
24 -  
25 - alias :meta_cache_key :cache_key  
26 - def cache_key  
27 - key = [Noosfero::VERSION, meta_cache_key]  
28 - key.unshift(ActiveRecord::Base.connection.schema_search_path) if ActiveRecord::Base.postgresql?  
29 - key.join('/')  
30 - end  
31 -  
32 - def self.like_search(query, options={})  
33 - if defined?(self::SEARCHABLE_FIELDS) || options[:fields].present?  
34 - fields_per_table = {}  
35 - fields_per_table[table_name] = (options[:fields].present? ? options[:fields] : self::SEARCHABLE_FIELDS.keys.map(&:to_s)) & column_names  
36 -  
37 - if options[:joins].present?  
38 - join_asset = options[:joins].to_s.classify.constantize  
39 - if defined?(join_asset::SEARCHABLE_FIELDS) || options[:fields].present?  
40 - fields_per_table[join_asset.table_name] = (options[:fields].present? ? options[:fields] : join_asset::SEARCHABLE_FIELDS.keys.map(&:to_s)) & join_asset.column_names  
41 - end  
42 - end  
43 -  
44 - query = query.downcase.strip  
45 - fields_per_table.delete_if { |table,fields| fields.blank? }  
46 - conditions = fields_per_table.map do |table,fields|  
47 - fields.map do |field|  
48 - "lower(#{table}.#{field}) LIKE '%#{query}%'"  
49 - end.join(' OR ')  
50 - end.join(' OR ')  
51 -  
52 - if options[:joins].present?  
53 - joins(options[:joins]).where(conditions)  
54 - else  
55 - where(conditions)  
56 - end  
57 -  
58 - else  
59 - raise "No searchable fields defined for #{self.name}"  
60 - end  
61 - end  
62 -  
63 -end  
64 -  
65 -ActiveRecord::Calculations.class_eval do  
66 - def count_with_distinct column_name=self.primary_key  
67 - if column_name  
68 - distinct.count_without_distinct column_name  
69 - else  
70 - count_without_distinct  
71 - end  
72 - end  
73 - alias_method_chain :count, :distinct  
74 -end  
lib/noosfero/core_ext/active_record/calculations.rb 0 → 100644
@@ -0,0 +1,10 @@ @@ -0,0 +1,10 @@
  1 +ActiveRecord::Calculations.class_eval do
  2 + def count_with_distinct column_name=self.primary_key
  3 + if column_name
  4 + distinct.count_without_distinct column_name
  5 + else
  6 + count_without_distinct
  7 + end
  8 + end
  9 + alias_method_chain :count, :distinct
  10 +end
lib/noosfero/multi_tenancy.rb
@@ -12,12 +12,12 @@ module Noosfero @@ -12,12 +12,12 @@ module Noosfero
12 def self.db_by_host=(host) 12 def self.db_by_host=(host)
13 if host != @db_by_host 13 if host != @db_by_host
14 @db_by_host = host 14 @db_by_host = host
15 - ActiveRecord::Base.connection.schema_search_path = self.mapping[host] 15 + ApplicationRecord.connection.schema_search_path = self.mapping[host]
16 end 16 end
17 end 17 end
18 18
19 def self.setup!(host) 19 def self.setup!(host)
20 - if Noosfero::MultiTenancy.on? and ActiveRecord::Base.postgresql? 20 + if Noosfero::MultiTenancy.on? and ApplicationRecord.postgresql?
21 Noosfero::MultiTenancy.db_by_host = host 21 Noosfero::MultiTenancy.db_by_host = host
22 end 22 end
23 end 23 end
lib/noosfero/unicorn.rb
@@ -7,11 +7,11 @@ GC.respond_to?(:copy_on_write_friendly=) and @@ -7,11 +7,11 @@ GC.respond_to?(:copy_on_write_friendly=) and
7 GC.copy_on_write_friendly = true 7 GC.copy_on_write_friendly = true
8 8
9 before_fork do |server, worker| 9 before_fork do |server, worker|
10 - ActiveRecord::Base.connection.disconnect! if defined?(ActiveRecord::Base) 10 + ApplicationRecord.connection.disconnect! if defined?(ApplicationRecord)
11 end 11 end
12 12
13 after_fork do |server, worker| 13 after_fork do |server, worker|
14 - ActiveRecord::Base.establish_connection if defined?(ActiveRecord::Base) 14 + ApplicationRecord.establish_connection if defined?(ApplicationRecord)
15 end 15 end
16 16
17 # load local configuration file, if it exists 17 # load local configuration file, if it exists
lib/postgresql_attachment_fu.rb
@@ -9,11 +9,12 @@ module PostgresqlAttachmentFu @@ -9,11 +9,12 @@ module PostgresqlAttachmentFu
9 module InstanceMethods 9 module InstanceMethods
10 def full_filename(thumbnail = nil) 10 def full_filename(thumbnail = nil)
11 file_system_path = (thumbnail ? thumbnail_class : self).attachment_options[:path_prefix].to_s 11 file_system_path = (thumbnail ? thumbnail_class : self).attachment_options[:path_prefix].to_s
12 - file_system_path = File.join(file_system_path, ActiveRecord::Base.connection.schema_search_path) if ActiveRecord::Base.postgresql? and Noosfero::MultiTenancy.on? 12 + file_system_path = File.join(file_system_path, ApplicationRecord.connection.schema_search_path) if ApplicationRecord.postgresql? and Noosfero::MultiTenancy.on?
13 Rails.root.join(file_system_path, *partitioned_path(thumbnail_name_for(thumbnail))).to_s 13 Rails.root.join(file_system_path, *partitioned_path(thumbnail_name_for(thumbnail))).to_s
14 end 14 end
15 end 15 end
16 16
17 end 17 end
18 18
19 -ActiveRecord::Base.send(:extend, PostgresqlAttachmentFu::ClassMethods) 19 +ApplicationRecord.extend PostgresqlAttachmentFu::ClassMethods
  20 +
lib/split_datetime.rb
@@ -69,4 +69,5 @@ module SplitDatetime @@ -69,4 +69,5 @@ module SplitDatetime
69 end 69 end
70 70
71 Class.extend SplitDatetime::SplitMethods 71 Class.extend SplitDatetime::SplitMethods
72 -ActiveRecord::Base.extend SplitDatetime::SplitMethods 72 +ApplicationRecord.extend SplitDatetime::SplitMethods
  73 +
lib/sqlite_extension.rb
1 -if ActiveRecord::Base.connection.adapter_name.downcase == 'sqlite' 1 +if ApplicationRecord.connection.adapter_name.downcase == 'sqlite'
2 2
3 - database = ActiveRecord::Base.connection.raw_connection 3 + database = ApplicationRecord.connection.raw_connection
4 4
5 database.create_function('pow', 2, 1) do |func, base, exponent| 5 database.create_function('pow', 2, 1) do |func, base, exponent|
6 func.set_result(base.to_f ** exponent.to_f) 6 func.set_result(base.to_f ** exponent.to_f)
7 end 7 end
8 - 8 +
9 database.create_function('sqrt', 1, 1) do |func, value| 9 database.create_function('sqrt', 1, 1) do |func, value|
10 func.set_result(Math.sqrt(value)) 10 func.set_result(Math.sqrt(value))
11 end 11 end
@@ -18,8 +18,8 @@ if ActiveRecord::Base.connection.adapter_name.downcase == &#39;sqlite&#39; @@ -18,8 +18,8 @@ if ActiveRecord::Base.connection.adapter_name.downcase == &#39;sqlite&#39;
18 func.set_result( 18 func.set_result(
19 radius.to_f * Math.acos( 19 radius.to_f * Math.acos(
20 [1, 20 [1,
21 - Math.cos(lat1.to_f) * Math.cos(long1.to_f) * Math.cos(lat2.to_f) * Math.cos(long2.to_f) +  
22 - Math.cos(lat1.to_f) * Math.sin(long1.to_f) * Math.cos(lat2.to_f) * Math.sin(long2.to_f) + 21 + Math.cos(lat1.to_f) * Math.cos(long1.to_f) * Math.cos(lat2.to_f) * Math.cos(long2.to_f) +
  22 + Math.cos(lat1.to_f) * Math.sin(long1.to_f) * Math.cos(lat2.to_f) * Math.sin(long2.to_f) +
23 Math.sin(lat1.to_f) * Math.sin(lat2.to_f) 23 Math.sin(lat1.to_f) * Math.sin(lat2.to_f)
24 ].min 24 ].min
25 ) 25 )
lib/tasks/backup.rake
@@ -115,7 +115,7 @@ end @@ -115,7 +115,7 @@ end
115 115
116 desc 'Removes emails from database' 116 desc 'Removes emails from database'
117 task 'restore:remove_emails' => :environment do 117 task 'restore:remove_emails' => :environment do
118 - connection = ActiveRecord::Base.connection 118 + connection = ApplicationRecord.connection
119 [ 119 [
120 "UPDATE users SET email = concat('user', id, '@localhost.localdomain')", 120 "UPDATE users SET email = concat('user', id, '@localhost.localdomain')",
121 "UPDATE environments SET contact_email = concat('environment', id, '@localhost.localdomain')", 121 "UPDATE environments SET contact_email = concat('environment', id, '@localhost.localdomain')",
lib/tasks/multitenancy.rake
1 namespace :multitenancy do 1 namespace :multitenancy do
2 2
3 task :create => :environment do 3 task :create => :environment do
4 - db_envs = ActiveRecord::Base.configurations.keys.select{ |k| k.match(/_development$|_production$|_test$/) } 4 + db_envs = ApplicationRecord.configurations.keys.select{ |k| k.match(/_development$|_production$|_test$/) }
5 cd Rails.root.join('config', 'environments'), :verbose => true 5 cd Rails.root.join('config', 'environments'), :verbose => true
6 file_envs = Dir.glob "{*_development.rb,*_production.rb,*_test.rb}" 6 file_envs = Dir.glob "{*_development.rb,*_production.rb,*_test.rb}"
7 (db_envs.map{ |e| e + '.rb' } - file_envs).each { |env| ln_s env.split('_').last, env } 7 (db_envs.map{ |e| e + '.rb' } - file_envs).each { |env| ln_s env.split('_').last, env }
8 end 8 end
9 9
10 task :remove => :environment do 10 task :remove => :environment do
11 - db_envs = ActiveRecord::Base.configurations.keys.select{ |k| k.match(/_development$|_production$|_test$/) } 11 + db_envs = ApplicationRecord.configurations.keys.select{ |k| k.match(/_development$|_production$|_test$/) }
12 cd Rails.root.join('config', 'environments'), :verbose => true 12 cd Rails.root.join('config', 'environments'), :verbose => true
13 file_envs = Dir.glob "{*_development.rb,*_production.rb,*_test.rb}" 13 file_envs = Dir.glob "{*_development.rb,*_production.rb,*_test.rb}"
14 (file_envs - db_envs.map{ |e| e + '.rb' }).each { |env| safe_unlink env } 14 (file_envs - db_envs.map{ |e| e + '.rb' }).each { |env| safe_unlink env }
@@ -19,7 +19,7 @@ end @@ -19,7 +19,7 @@ end
19 namespace :db do 19 namespace :db do
20 20
21 task :migrate_other_environments => :environment do 21 task :migrate_other_environments => :environment do
22 - envs = ActiveRecord::Base.configurations.keys.select{ |k| k.match(/_#{Rails.env}$/) } 22 + envs = ApplicationRecord.configurations.keys.select{ |k| k.match(/_#{Rails.env}$/) }
23 envs.each do |e| 23 envs.each do |e|
24 puts "*** Migrating #{e}" if Rake.application.options.trace 24 puts "*** Migrating #{e}" if Rake.application.options.trace
25 system "rake db:migrate RAILS_ENV=#{e} SCHEMA=/dev/null" 25 system "rake db:migrate RAILS_ENV=#{e} SCHEMA=/dev/null"
lib/upload_sanitizer.rb
@@ -10,4 +10,4 @@ module UploadSanitizer @@ -10,4 +10,4 @@ module UploadSanitizer
10 end 10 end
11 end 11 end
12 12
13 -ActiveRecord::Base.send(:include, UploadSanitizer) 13 +ApplicationRecord.send :include, UploadSanitizer
plugins/analytics/models/analytics_plugin/page_view.rb
1 -class AnalyticsPlugin::PageView < ActiveRecord::Base 1 +class AnalyticsPlugin::PageView < ApplicationRecord
2 2
3 serialize :data 3 serialize :data
4 4
plugins/analytics/models/analytics_plugin/visit.rb
1 -class AnalyticsPlugin::Visit < ActiveRecord::Base 1 +class AnalyticsPlugin::Visit < ApplicationRecord
2 2
3 attr_accessible *self.column_names 3 attr_accessible *self.column_names
4 attr_accessible :profile 4 attr_accessible :profile
plugins/comment_classification/lib/comment_classification_plugin/comment_label_user.rb
1 -class CommentClassificationPlugin::CommentLabelUser < ActiveRecord::Base 1 +class CommentClassificationPlugin::CommentLabelUser < ApplicationRecord
2 self.table_name = :comment_classification_plugin_comment_label_user 2 self.table_name = :comment_classification_plugin_comment_label_user
3 3
4 belongs_to :profile 4 belongs_to :profile
plugins/comment_classification/lib/comment_classification_plugin/comment_status_user.rb
1 -class CommentClassificationPlugin::CommentStatusUser < ActiveRecord::Base 1 +class CommentClassificationPlugin::CommentStatusUser < ApplicationRecord
2 self.table_name = :comment_classification_plugin_comment_status_user 2 self.table_name = :comment_classification_plugin_comment_status_user
3 3
4 belongs_to :profile 4 belongs_to :profile
plugins/comment_classification/lib/comment_classification_plugin/label.rb
1 -class CommentClassificationPlugin::Label < ActiveRecord::Base 1 +class CommentClassificationPlugin::Label < ApplicationRecord
2 2
3 belongs_to :owner, :polymorphic => true 3 belongs_to :owner, :polymorphic => true
4 4
plugins/comment_classification/lib/comment_classification_plugin/status.rb
1 -class CommentClassificationPlugin::Status < ActiveRecord::Base 1 +class CommentClassificationPlugin::Status < ApplicationRecord
2 2
3 belongs_to :owner, :polymorphic => true 3 belongs_to :owner, :polymorphic => true
4 4
plugins/custom_forms/db/migrate/20130823151900_associate_fields_to_alternatives.rb
1 class AssociateFieldsToAlternatives < ActiveRecord::Migration 1 class AssociateFieldsToAlternatives < ActiveRecord::Migration
2 - class CustomFormsPlugin::Field < ActiveRecord::Base 2 + class CustomFormsPlugin::Field < ApplicationRecord
3 self.table_name = :custom_forms_plugin_fields 3 self.table_name = :custom_forms_plugin_fields
4 has_many :alternatives, :class_name => 'CustomFormsPlugin::Alternative' 4 has_many :alternatives, :class_name => 'CustomFormsPlugin::Alternative'
5 serialize :choices, Hash 5 serialize :choices, Hash
plugins/custom_forms/lib/custom_forms_plugin/alternative.rb
1 -class CustomFormsPlugin::Alternative < ActiveRecord::Base 1 +class CustomFormsPlugin::Alternative < ApplicationRecord
2 self.table_name = :custom_forms_plugin_alternatives 2 self.table_name = :custom_forms_plugin_alternatives
3 3
4 validates_presence_of :label 4 validates_presence_of :label
plugins/custom_forms/lib/custom_forms_plugin/answer.rb
1 -class CustomFormsPlugin::Answer < ActiveRecord::Base 1 +class CustomFormsPlugin::Answer < ApplicationRecord
2 self.table_name = :custom_forms_plugin_answers 2 self.table_name = :custom_forms_plugin_answers
3 belongs_to :field, :class_name => 'CustomFormsPlugin::Field' 3 belongs_to :field, :class_name => 'CustomFormsPlugin::Field'
4 belongs_to :submission, :class_name => 'CustomFormsPlugin::Submission' 4 belongs_to :submission, :class_name => 'CustomFormsPlugin::Submission'
plugins/custom_forms/lib/custom_forms_plugin/field.rb
1 -class CustomFormsPlugin::Field < ActiveRecord::Base 1 +class CustomFormsPlugin::Field < ApplicationRecord
2 self.table_name = :custom_forms_plugin_fields 2 self.table_name = :custom_forms_plugin_fields
3 3
4 validates_presence_of :name 4 validates_presence_of :name
plugins/custom_forms/lib/custom_forms_plugin/form.rb
1 -class CustomFormsPlugin::Form < ActiveRecord::Base 1 +class CustomFormsPlugin::Form < ApplicationRecord
2 2
3 belongs_to :profile 3 belongs_to :profile
4 4
plugins/custom_forms/lib/custom_forms_plugin/submission.rb
1 -class CustomFormsPlugin::Submission < ActiveRecord::Base 1 +class CustomFormsPlugin::Submission < ApplicationRecord
2 2
3 belongs_to :form, :class_name => 'CustomFormsPlugin::Form' 3 belongs_to :form, :class_name => 'CustomFormsPlugin::Form'
4 belongs_to :profile 4 belongs_to :profile
plugins/delivery/db/migrate/20130719132252_create_delivery_plugin_tables.rb
1 class CreateDeliveryPluginTables < ActiveRecord::Migration 1 class CreateDeliveryPluginTables < ActiveRecord::Migration
2 def self.up 2 def self.up
3 # check if distribution plugin already moved tables 3 # check if distribution plugin already moved tables
4 - return if ActiveRecord::Base.connection.table_exists? :delivery_plugin_methods 4 + return if ApplicationRecord.connection.table_exists? :delivery_plugin_methods
5 5
6 create_table :delivery_plugin_methods do |t| 6 create_table :delivery_plugin_methods do |t|
7 t.integer :profile_id 7 t.integer :profile_id
plugins/delivery/models/delivery_plugin/method.rb
1 -class DeliveryPlugin::Method < ActiveRecord::Base 1 +class DeliveryPlugin::Method < ApplicationRecord
2 2
3 Types = ['pickup', 'deliver'] 3 Types = ['pickup', 'deliver']
4 4
plugins/delivery/models/delivery_plugin/option.rb
1 -class DeliveryPlugin::Option < ActiveRecord::Base 1 +class DeliveryPlugin::Option < ApplicationRecord
2 2
3 belongs_to :delivery_method, :class_name => 'DeliveryPlugin::Method' 3 belongs_to :delivery_method, :class_name => 'DeliveryPlugin::Method'
4 belongs_to :owner, :polymorphic => true 4 belongs_to :owner, :polymorphic => true
plugins/driven_signup/models/driven_signup_plugin/auth.rb
1 -class DrivenSignupPlugin::Auth < ActiveRecord::Base 1 +class DrivenSignupPlugin::Auth < ApplicationRecord
2 2
3 attr_accessible :name, :token 3 attr_accessible :name, :token
4 4
plugins/environment_notification/lib/environment_notifications_user.rb
1 -class EnvironmentNotificationsUser < ActiveRecord::Base 1 +class EnvironmentNotificationsUser < ApplicationRecord
2 self.table_name = "environment_notifications_users" 2 self.table_name = "environment_notifications_users"
3 3
4 belongs_to :user 4 belongs_to :user
plugins/environment_notification/models/environment_notification_plugin/environment_notification.rb
1 -class EnvironmentNotificationPlugin::EnvironmentNotification < ActiveRecord::Base 1 +class EnvironmentNotificationPlugin::EnvironmentNotification < ApplicationRecord
2 2
3 self.table_name = "environment_notifications" 3 self.table_name = "environment_notifications"
4 4
plugins/fb_app/models/fb_app_plugin/page_tab.rb
1 -class FbAppPlugin::PageTab < ActiveRecord::Base 1 +class FbAppPlugin::PageTab < ApplicationRecord
2 2
3 # FIXME: rename table to match model 3 # FIXME: rename table to match model
4 self.table_name = :fb_app_plugin_page_tab_configs 4 self.table_name = :fb_app_plugin_page_tab_configs
plugins/foo/lib/foo_plugin/bar.rb
1 -class FooPlugin::Bar < ActiveRecord::Base 1 +class FooPlugin::Bar < ApplicationRecord
2 2
3 end 3 end
plugins/lattes_curriculum/lib/academic_info.rb
1 -class AcademicInfo < ActiveRecord::Base 1 +class AcademicInfo < ApplicationRecord
2 2
3 belongs_to :person 3 belongs_to :person
4 4
plugins/mark_comment_as_read/lib/mark_comment_as_read_plugin/read_comments.rb
1 -class MarkCommentAsReadPlugin::ReadComments < ActiveRecord::Base 1 +class MarkCommentAsReadPlugin::ReadComments < ApplicationRecord
2 self.table_name = 'mark_comment_as_read_plugin' 2 self.table_name = 'mark_comment_as_read_plugin'
3 belongs_to :comment 3 belongs_to :comment
4 belongs_to :person 4 belongs_to :person
plugins/metadata/lib/metadata_plugin/base.rb
@@ -71,6 +71,6 @@ end @@ -71,6 +71,6 @@ end
71 71
72 ActiveSupport.run_load_hooks :metadata_plugin, MetadataPlugin 72 ActiveSupport.run_load_hooks :metadata_plugin, MetadataPlugin
73 ActiveSupport.on_load :active_record do 73 ActiveSupport.on_load :active_record do
74 - ActiveRecord::Base.extend MetadataPlugin::Specs::ClassMethods 74 + ApplicationRecord.extend MetadataPlugin::Specs::ClassMethods
75 end 75 end
76 76
plugins/newsletter/lib/newsletter_plugin/newsletter.rb
1 require 'csv' 1 require 'csv'
2 2
3 -class NewsletterPlugin::Newsletter < ActiveRecord::Base 3 +class NewsletterPlugin::Newsletter < ApplicationRecord
4 4
5 belongs_to :environment 5 belongs_to :environment
6 belongs_to :person 6 belongs_to :person
plugins/oauth_client/models/oauth_client_plugin/auth.rb
1 -class OauthClientPlugin::Auth < ActiveRecord::Base 1 +class OauthClientPlugin::Auth < ApplicationRecord
2 2
3 attr_accessible :profile, :provider, :enabled, 3 attr_accessible :profile, :provider, :enabled,
4 :access_token, :expires_in 4 :access_token, :expires_in
plugins/oauth_client/models/oauth_client_plugin/provider.rb
1 -class OauthClientPlugin::Provider < ActiveRecord::Base 1 +class OauthClientPlugin::Provider < ApplicationRecord
2 2
3 belongs_to :environment 3 belongs_to :environment
4 4
plugins/open_graph/models/open_graph_plugin/track.rb
1 -class OpenGraphPlugin::Track < ActiveRecord::Base 1 +class OpenGraphPlugin::Track < ApplicationRecord
2 2
3 class_attribute :context 3 class_attribute :context
4 self.context = :open_graph 4 self.context = :open_graph
plugins/orders/db/migrate/20130719132245_create_orders_plugin_tables.rb
1 class CreateOrdersPluginTables < ActiveRecord::Migration 1 class CreateOrdersPluginTables < ActiveRecord::Migration
2 def self.up 2 def self.up
3 # check if distribution plugin already moved tables 3 # check if distribution plugin already moved tables
4 - return if ActiveRecord::Base.connection.table_exists? :orders_plugin_orders 4 + return if ApplicationRecord.connection.table_exists? :orders_plugin_orders
5 5
6 create_table :orders_plugin_orders do |t| 6 create_table :orders_plugin_orders do |t|
7 t.integer :profile_id 7 t.integer :profile_id
plugins/orders/lib/code_numbering.rb
@@ -55,4 +55,4 @@ module CodeNumbering @@ -55,4 +55,4 @@ module CodeNumbering
55 end 55 end
56 end 56 end
57 57
58 -ActiveRecord::Base.extend CodeNumbering::ClassMethods 58 +ApplicationRecord.extend CodeNumbering::ClassMethods
plugins/orders/lib/serialized_synced_data.rb
@@ -56,7 +56,7 @@ module SerializedSyncedData @@ -56,7 +56,7 @@ module SerializedSyncedData
56 source = self.send field 56 source = self.send field
57 if block_given? 57 if block_given?
58 data = SerializedSyncedData.prepare_data instance_exec(source, &block) 58 data = SerializedSyncedData.prepare_data instance_exec(source, &block)
59 - elsif source.is_a? ActiveRecord::Base 59 + elsif source.is_a? ApplicationRecord
60 data = SerializedSyncedData.prepare_data source.attributes 60 data = SerializedSyncedData.prepare_data source.attributes
61 elsif source.is_a? Array 61 elsif source.is_a? Array
62 data = source.map{ |source| SerializedSyncedData.prepare_data source.attributes } 62 data = source.map{ |source| SerializedSyncedData.prepare_data source.attributes }
plugins/orders/models/orders_plugin/item.rb
1 -class OrdersPlugin::Item < ActiveRecord::Base 1 +class OrdersPlugin::Item < ApplicationRecord
2 2
3 attr_accessible :order, :sale, :purchase, 3 attr_accessible :order, :sale, :purchase,
4 :product, :product_id, 4 :product, :product_id,
plugins/orders/models/orders_plugin/order.rb
1 -class OrdersPlugin::Order < ActiveRecord::Base 1 +class OrdersPlugin::Order < ApplicationRecord
2 2
3 # if abstract_class is true then it will trigger https://github.com/rails/rails/issues/20871 3 # if abstract_class is true then it will trigger https://github.com/rails/rails/issues/20871
4 #self.abstract_class = true 4 #self.abstract_class = true
plugins/orders_cycle/db/migrate/20130909175738_create_orders_cycle_plugin_tables.rb
@@ -2,7 +2,7 @@ class CreateOrdersCyclePluginTables &lt; ActiveRecord::Migration @@ -2,7 +2,7 @@ class CreateOrdersCyclePluginTables &lt; ActiveRecord::Migration
2 2
3 def change 3 def change
4 # check if distribution plugin already moved the table 4 # check if distribution plugin already moved the table
5 - return if ActiveRecord::Base.connection.table_exists? :orders_cycle_plugin_cycles 5 + return if ApplicationRecord.connection.table_exists? :orders_cycle_plugin_cycles
6 6
7 create_table :orders_cycle_plugin_cycle_orders do |t| 7 create_table :orders_cycle_plugin_cycle_orders do |t|
8 t.integer :cycle_id 8 t.integer :cycle_id
plugins/orders_cycle/models/orders_cycle_plugin/cycle.rb
1 -class OrdersCyclePlugin::Cycle < ActiveRecord::Base 1 +class OrdersCyclePlugin::Cycle < ApplicationRecord
2 2
3 attr_accessible :profile, :status, :name, :description, :opening_message 3 attr_accessible :profile, :status, :name, :description, :opening_message
4 4
@@ -233,7 +233,7 @@ class OrdersCyclePlugin::Cycle &lt; ActiveRecord::Base @@ -233,7 +233,7 @@ class OrdersCyclePlugin::Cycle &lt; ActiveRecord::Base
233 233
234 def add_products 234 def add_products
235 return if self.products.count > 0 235 return if self.products.count > 0
236 - ActiveRecord::Base.transaction do 236 + ApplicationRecord.transaction do
237 self.profile.products.supplied.unarchived.available.find_each batch_size: 20 do |product| 237 self.profile.products.supplied.unarchived.available.find_each batch_size: 20 do |product|
238 self.add_product product 238 self.add_product product
239 end 239 end
plugins/orders_cycle/models/orders_cycle_plugin/cycle_order.rb
1 -class OrdersCyclePlugin::CycleOrder < ActiveRecord::Base 1 +class OrdersCyclePlugin::CycleOrder < ApplicationRecord
2 2
3 belongs_to :cycle, class_name: 'OrdersCyclePlugin::Cycle' 3 belongs_to :cycle, class_name: 'OrdersCyclePlugin::Cycle'
4 belongs_to :sale, class_name: 'OrdersCyclePlugin::Sale', foreign_key: :sale_id, dependent: :destroy 4 belongs_to :sale, class_name: 'OrdersCyclePlugin::Sale', foreign_key: :sale_id, dependent: :destroy
plugins/orders_cycle/models/orders_cycle_plugin/cycle_product.rb
1 -class OrdersCyclePlugin::CycleProduct < ActiveRecord::Base 1 +class OrdersCyclePlugin::CycleProduct < ApplicationRecord
2 2
3 self.table_name = :orders_cycle_plugin_cycle_products 3 self.table_name = :orders_cycle_plugin_cycle_products
4 4
plugins/orders_cycle/models/orders_cycle_plugin/sale.rb
@@ -34,7 +34,7 @@ class OrdersCyclePlugin::Sale &lt; OrdersPlugin::Sale @@ -34,7 +34,7 @@ class OrdersCyclePlugin::Sale &lt; OrdersPlugin::Sale
34 end 34 end
35 35
36 def add_purchases_items 36 def add_purchases_items
37 - ActiveRecord::Base.transaction do 37 + ApplicationRecord.transaction do
38 self.items.each do |item| 38 self.items.each do |item|
39 next unless supplier_product = item.product.supplier_product 39 next unless supplier_product = item.product.supplier_product
40 next unless supplier = supplier_product.profile 40 next unless supplier = supplier_product.profile
@@ -54,7 +54,7 @@ class OrdersCyclePlugin::Sale &lt; OrdersPlugin::Sale @@ -54,7 +54,7 @@ class OrdersCyclePlugin::Sale &lt; OrdersPlugin::Sale
54 end 54 end
55 55
56 def remove_purchases_items 56 def remove_purchases_items
57 - ActiveRecord::Base.transaction do 57 + ApplicationRecord.transaction do
58 self.items.each do |item| 58 self.items.each do |item|
59 next unless supplier_product = item.product.supplier_product 59 next unless supplier_product = item.product.supplier_product
60 next unless purchase = supplier_product.orders_cycles_purchases.for_cycle(self.cycle).first 60 next unless purchase = supplier_product.orders_cycles_purchases.for_cycle(self.cycle).first
plugins/organization_ratings/lib/organization_rating.rb
1 -class OrganizationRating < ActiveRecord::Base 1 +class OrganizationRating < ApplicationRecord
2 belongs_to :person 2 belongs_to :person
3 belongs_to :organization 3 belongs_to :organization
4 belongs_to :comment 4 belongs_to :comment
plugins/organization_ratings/lib/organization_ratings_config.rb
1 -class OrganizationRatingsConfig < ActiveRecord::Base 1 +class OrganizationRatingsConfig < ApplicationRecord
2 2
3 belongs_to :environment 3 belongs_to :environment
4 4
plugins/pg_search/lib/ext/active_record.rb
@@ -1,17 +0,0 @@ @@ -1,17 +0,0 @@
1 -require_dependency 'active_record'  
2 -  
3 -class ActiveRecord::Base  
4 - def self.pg_search_plugin_search(query)  
5 - filtered_query = query.gsub(/[\|\(\)\\\/\s\[\]'"*%&!:]/,' ').split.map{|w| w += ":*"}.join('|')  
6 - if defined?(self::SEARCHABLE_FIELDS)  
7 - where("to_tsvector('simple', #{pg_search_plugin_fields}) @@ to_tsquery('#{filtered_query}')").  
8 - order("ts_rank(to_tsvector('simple', #{pg_search_plugin_fields}), to_tsquery('#{filtered_query}')) DESC")  
9 - else  
10 - raise "No searchable fields defined for #{self.name}"  
11 - end  
12 - end  
13 -  
14 - def self.pg_search_plugin_fields  
15 - self::SEARCHABLE_FIELDS.keys.map(&:to_s).sort.map {|f| "coalesce(#{table_name}.#{f}, '')"}.join(" || ' ' || ")  
16 - end  
17 -end  
plugins/pg_search/lib/ext/application_record.rb 0 → 100644
@@ -0,0 +1,19 @@ @@ -0,0 +1,19 @@
  1 +require_dependency 'application_record'
  2 +
  3 +class ApplicationRecord
  4 +
  5 + def self.pg_search_plugin_search(query)
  6 + filtered_query = query.gsub(/[\|\(\)\\\/\s\[\]'"*%&!:]/,' ').split.map{|w| w += ":*"}.join('|')
  7 + if defined?(self::SEARCHABLE_FIELDS)
  8 + where("to_tsvector('simple', #{pg_search_plugin_fields}) @@ to_tsquery('#{filtered_query}')").
  9 + order("ts_rank(to_tsvector('simple', #{pg_search_plugin_fields}), to_tsquery('#{filtered_query}')) DESC")
  10 + else
  11 + raise "No searchable fields defined for #{self.name}"
  12 + end
  13 + end
  14 +
  15 + def self.pg_search_plugin_fields
  16 + self::SEARCHABLE_FIELDS.keys.map(&:to_s).sort.map {|f| "coalesce(#{table_name}.#{f}, '')"}.join(" || ' ' || ")
  17 + end
  18 +
  19 +end
plugins/push_notification/lib/device_token.rb
1 -class PushNotificationPlugin::DeviceToken < ActiveRecord::Base 1 +class PushNotificationPlugin::DeviceToken < ApplicationRecord
2 belongs_to :user 2 belongs_to :user
3 attr_accessible :token, :device_name, :user 3 attr_accessible :token, :device_name, :user
4 4
plugins/push_notification/lib/notification_settings.rb
1 -class PushNotificationPlugin::NotificationSettings < ActiveRecord::Base 1 +class PushNotificationPlugin::NotificationSettings < ApplicationRecord
2 2
3 NOTIFICATIONS= { 3 NOTIFICATIONS= {
4 "add_friend" => 0x1, 4 "add_friend" => 0x1,
plugins/push_notification/lib/notification_subscription.rb
1 -class PushNotificationPlugin::NotificationSubscription < ActiveRecord::Base 1 +class PushNotificationPlugin::NotificationSubscription < ApplicationRecord
  2 +
2 belongs_to :environment 3 belongs_to :environment
3 attr_accessible :subscribers, :notification, :environment 4 attr_accessible :subscribers, :notification, :environment
4 5
plugins/shopping_cart/db/migrate/20131226125124_move_shopping_cart_purchase_order_to_orders_plugin_order.rb
1 OrdersPlugin.send :remove_const, :Item if defined? OrdersPlugin::Item 1 OrdersPlugin.send :remove_const, :Item if defined? OrdersPlugin::Item
2 OrdersPlugin.send :remove_const, :Order if defined? OrdersPlugin::Order 2 OrdersPlugin.send :remove_const, :Order if defined? OrdersPlugin::Order
3 3
4 -class ShoppingCartPlugin::PurchaseOrder < ActiveRecord::Base 4 +class ShoppingCartPlugin::PurchaseOrder < ApplicationRecord
5 acts_as_having_settings field: :data 5 acts_as_having_settings field: :data
6 6
7 module Status 7 module Status
@@ -16,10 +16,10 @@ class Profile @@ -16,10 +16,10 @@ class Profile
16 has_many :orders, class_name: 'OrdersPlugin::Order' 16 has_many :orders, class_name: 'OrdersPlugin::Order'
17 end 17 end
18 18
19 -class OrdersPlugin::Item < ActiveRecord::Base 19 +class OrdersPlugin::Item < ApplicationRecord
20 belongs_to :order, class_name: 'OrdersPlugin::Order' 20 belongs_to :order, class_name: 'OrdersPlugin::Order'
21 end 21 end
22 -class OrdersPlugin::Order < ActiveRecord::Base 22 +class OrdersPlugin::Order < ApplicationRecord
23 has_many :items, class_name: 'OrdersPlugin::Item', foreign_key: :order_id 23 has_many :items, class_name: 'OrdersPlugin::Item', foreign_key: :order_id
24 24
25 extend CodeNumbering::ClassMethods 25 extend CodeNumbering::ClassMethods
plugins/sniffer/db/migrate/20131212124106_drop_sniffer_profile_table.rb
1 SnifferPlugin.send :remove_const, :Opportunity if defined? SnifferPlugin::Opportunity 1 SnifferPlugin.send :remove_const, :Opportunity if defined? SnifferPlugin::Opportunity
2 2
3 -class SnifferPlugin::Profile < ActiveRecord::Base 3 +class SnifferPlugin::Profile < ApplicationRecord
4 belongs_to :profile 4 belongs_to :profile
5 end 5 end
6 -class SnifferPlugin::Opportunity < ActiveRecord::Base 6 +class SnifferPlugin::Opportunity < ApplicationRecord
7 belongs_to :sniffer_profile, class_name: 'SnifferPlugin::Profile', foreign_key: :profile_id 7 belongs_to :sniffer_profile, class_name: 'SnifferPlugin::Profile', foreign_key: :profile_id
8 end 8 end
9 9
plugins/sniffer/models/sniffer_plugin/opportunity.rb
1 -class SnifferPlugin::Opportunity < ActiveRecord::Base 1 +class SnifferPlugin::Opportunity < ApplicationRecord
2 2
3 self.table_name = :sniffer_plugin_opportunities 3 self.table_name = :sniffer_plugin_opportunities
4 4
plugins/solr/lib/acts_as_faceted.rb
@@ -191,32 +191,5 @@ module ActsAsFaceted @@ -191,32 +191,5 @@ module ActsAsFaceted
191 191
192 end 192 end
193 193
194 -ActiveRecord::Base.extend ActsAsFaceted::ActsMethods  
195 -  
196 -# from https://github.com/rubyworks/facets/blob/master/lib/core/facets/enumerable/graph.rb  
197 -module Enumerable  
198 - def graph(&yld)  
199 - if yld  
200 - h = {}  
201 - each do |*kv|  
202 - r = yld[*kv]  
203 - case r  
204 - when Hash  
205 - nk, nv = *r.to_a[0]  
206 - when Range  
207 - nk, nv = r.first, r.last  
208 - else  
209 - nk, nv = *r  
210 - end  
211 - h[nk] = nv  
212 - end  
213 - h  
214 - else  
215 - Enumerator.new(self,:graph)  
216 - end  
217 - end  
218 -  
219 - # Alias for #graph, which stands for "map hash".  
220 - alias_method :mash, :graph  
221 -end 194 +ApplicationRecord.extend ActsAsFaceted::ActsMethods
222 195
plugins/solr/lib/acts_as_searchable.rb
@@ -35,7 +35,7 @@ module ActsAsSearchable @@ -35,7 +35,7 @@ module ActsAsSearchable
35 module FindByContents 35 module FindByContents
36 36
37 def schema_name 37 def schema_name
38 - (Noosfero::MultiTenancy.on? and ActiveRecord::Base.postgresql?) ? ActiveRecord::Base.connection.schema_search_path : '' 38 + (Noosfero::MultiTenancy.on? and ApplicationRecord.postgresql?) ? ApplicationRecord.connection.schema_search_path : ''
39 end 39 end
40 40
41 def find_by_contents(query, pg_options = {}, options = {}, db_options = {}) 41 def find_by_contents(query, pg_options = {}, options = {}, db_options = {})
@@ -84,4 +84,5 @@ module ActsAsSearchable @@ -84,4 +84,5 @@ module ActsAsSearchable
84 end 84 end
85 end 85 end
86 86
87 -ActiveRecord::Base.send(:extend, ActsAsSearchable::ClassMethods) 87 +ApplicationRecord.extend ActsAsSearchable::ClassMethods
  88 +
plugins/solr/test/unit/acts_as_faceted_test.rb
@@ -2,11 +2,11 @@ require_relative &#39;../test_helper&#39; @@ -2,11 +2,11 @@ require_relative &#39;../test_helper&#39;
2 require "#{File.dirname(__FILE__)}/../../lib/acts_as_faceted" 2 require "#{File.dirname(__FILE__)}/../../lib/acts_as_faceted"
3 3
4 4
5 -class TestModel < ActiveRecord::Base 5 +class TestModel < ApplicationRecord
6 def self.f_type_proc(klass) 6 def self.f_type_proc(klass)
7 - klass.constantize 7 + klass.constantize
8 h = { 8 h = {
9 - 'UploadedFile' => "Uploaded File", 9 + 'UploadedFile' => "Uploaded File",
10 'TextArticle' => "Text", 10 'TextArticle' => "Text",
11 'Folder' => "Folder", 11 'Folder' => "Folder",
12 'Event' => "Event", 12 'Event' => "Event",
@@ -92,7 +92,7 @@ class ActsAsFacetedTest &lt; ActiveSupport::TestCase @@ -92,7 +92,7 @@ class ActsAsFacetedTest &lt; ActiveSupport::TestCase
92 assert_equivalent [["[* TO NOW-1YEARS/DAY]", "Older than one year", 10], ["[NOW-1YEARS TO NOW/DAY]", "Last year", 19]], r 92 assert_equivalent [["[* TO NOW-1YEARS/DAY]", "Older than one year", 10], ["[NOW-1YEARS TO NOW/DAY]", "Last year", 19]], r
93 end 93 end
94 94
95 - should 'return facet hash in map_facets_for' do 95 + should 'return facet hash in map_facets_for' do
96 r = TestModel.map_facets_for(Environment.default) 96 r = TestModel.map_facets_for(Environment.default)
97 assert r.count, 2 97 assert r.count, 2
98 98
@@ -147,7 +147,7 @@ class ActsAsFacetedTest &lt; ActiveSupport::TestCase @@ -147,7 +147,7 @@ class ActsAsFacetedTest &lt; ActiveSupport::TestCase
147 facets = TestModel.map_facets_for(Environment.default) 147 facets = TestModel.map_facets_for(Environment.default)
148 facet = facets.select{ |f| f[:id] == 'f_type' }.first 148 facet = facets.select{ |f| f[:id] == 'f_type' }.first
149 facet_data = TestModel.map_facet_results facet, @facet_params, @facets, @all_facets, {} 149 facet_data = TestModel.map_facet_results facet, @facet_params, @facets, @all_facets, {}
150 - sorted = TestModel.facet_result_sort(facet, facet_data, :alphabetically) 150 + sorted = TestModel.facet_result_sort(facet, facet_data, :alphabetically)
151 assert_equal sorted, 151 assert_equal sorted,
152 [["Folder", "Folder", 3], ["Gallery", "Gallery", 1], ["TextArticle", 'Text', 15], ["UploadedFile", "Uploaded File", 6]] 152 [["Folder", "Folder", 3], ["Gallery", "Gallery", 1], ["TextArticle", 'Text', 15], ["UploadedFile", "Uploaded File", 6]]
153 end 153 end
@@ -156,7 +156,7 @@ class ActsAsFacetedTest &lt; ActiveSupport::TestCase @@ -156,7 +156,7 @@ class ActsAsFacetedTest &lt; ActiveSupport::TestCase
156 facets = TestModel.map_facets_for(Environment.default) 156 facets = TestModel.map_facets_for(Environment.default)
157 facet = facets.select{ |f| f[:id] == 'f_type' }.first 157 facet = facets.select{ |f| f[:id] == 'f_type' }.first
158 facet_data = TestModel.map_facet_results facet, @facet_params, @facets, @all_facets, {} 158 facet_data = TestModel.map_facet_results facet, @facet_params, @facets, @all_facets, {}
159 - sorted = TestModel.facet_result_sort(facet, facet_data, :count) 159 + sorted = TestModel.facet_result_sort(facet, facet_data, :count)
160 assert_equal sorted, 160 assert_equal sorted,
161 [["TextArticle", "Text", 15], ["UploadedFile", "Uploaded File", 6], ["Folder", "Folder", 3], ["Gallery", "Gallery", 1]] 161 [["TextArticle", "Text", 15], ["UploadedFile", "Uploaded File", 6], ["Folder", "Folder", 3], ["Gallery", "Gallery", 1]]
162 end 162 end
plugins/solr/test/unit/acts_as_searchable_test.rb
@@ -23,7 +23,7 @@ class ActsAsSearchableTest &lt; ActiveSupport::TestCase @@ -23,7 +23,7 @@ class ActsAsSearchableTest &lt; ActiveSupport::TestCase
23 should 'not be searchable when disabled' do 23 should 'not be searchable when disabled' do
24 # suppress warning about already initialized constant 24 # suppress warning about already initialized constant
25 silent { ActsAsSearchable::ClassMethods::ACTS_AS_SEARCHABLE_ENABLED = false } 25 silent { ActsAsSearchable::ClassMethods::ACTS_AS_SEARCHABLE_ENABLED = false }
26 - 26 +
27 @test_model.expects(:acts_as_solr).never 27 @test_model.expects(:acts_as_solr).never
28 @test_model.acts_as_searchable 28 @test_model.acts_as_searchable
29 end 29 end
plugins/solr/vendor/plugins/acts_as_solr_reloaded/lib/acts_as_solr/dynamic_attribute.rb
1 -class DynamicAttribute < ActiveRecord::Base 1 +class DynamicAttribute < ApplicationRecord
2 belongs_to :dynamicable, :polymorphic => true 2 belongs_to :dynamicable, :polymorphic => true
3 end 3 end
plugins/spaminator/lib/spaminator_plugin/report.rb
1 -class SpaminatorPlugin::Report < ActiveRecord::Base 1 +class SpaminatorPlugin::Report < ApplicationRecord
2 2
3 serialize :failed, Hash 3 serialize :failed, Hash
4 4
plugins/stoa/lib/stoa_plugin/usp_aluno_turma_grad.rb
1 -class StoaPlugin::UspAlunoTurmaGrad < ActiveRecord::Base 1 +class StoaPlugin::UspAlunoTurmaGrad < ApplicationRecord
2 2
3 establish_connection(:stoa) 3 establish_connection(:stoa)
4 4
plugins/stoa/lib/stoa_plugin/usp_user.rb
1 -class StoaPlugin::UspUser < ActiveRecord::Base 1 +class StoaPlugin::UspUser < ApplicationRecord
2 2
3 establish_connection(:stoa) 3 establish_connection(:stoa)
4 self.table_name = 'pessoa' 4 self.table_name = 'pessoa'
plugins/stoa/test/functional/account_controller_test.rb
@@ -6,15 +6,15 @@ class AccountControllerTest &lt; ActionController::TestCase @@ -6,15 +6,15 @@ class AccountControllerTest &lt; ActionController::TestCase
6 SALT=YAML::load(File.open(StoaPlugin.root_path + 'config.yml'))['salt'] 6 SALT=YAML::load(File.open(StoaPlugin.root_path + 'config.yml'))['salt']
7 7
8 @db = Tempfile.new('stoa-test') 8 @db = Tempfile.new('stoa-test')
9 - configs = ActiveRecord::Base.configurations['stoa'] = {:adapter => 'sqlite3', :database => @db.path}  
10 - ActiveRecord::Base.establish_connection(:stoa) 9 + configs = ApplicationRecord.configurations['stoa'] = {:adapter => 'sqlite3', :database => @db.path}
  10 + ApplicationRecord.establish_connection(:stoa)
11 ActiveRecord::Schema.verbose = false 11 ActiveRecord::Schema.verbose = false
12 ActiveRecord::Schema.create_table "pessoa" do |t| 12 ActiveRecord::Schema.create_table "pessoa" do |t|
13 t.integer "codpes" 13 t.integer "codpes"
14 t.text "numcpf" 14 t.text "numcpf"
15 t.date "dtanas" 15 t.date "dtanas"
16 end 16 end
17 - ActiveRecord::Base.establish_connection(:test) 17 + ApplicationRecord.establish_connection(:test)
18 StoaPlugin::UspUser.reset_column_information 18 StoaPlugin::UspUser.reset_column_information
19 19
20 def setup 20 def setup
plugins/stoa/test/functional/profile_editor_controller_test.rb
@@ -13,7 +13,7 @@ class StoaPluginProfileEditorControllerTest &lt; ActionController::TestCase @@ -13,7 +13,7 @@ class StoaPluginProfileEditorControllerTest &lt; ActionController::TestCase
13 login_as(@person.identifier) 13 login_as(@person.identifier)
14 Environment.default.enable_plugin(StoaPlugin.name) 14 Environment.default.enable_plugin(StoaPlugin.name)
15 db = Tempfile.new('stoa-test') 15 db = Tempfile.new('stoa-test')
16 - ActiveRecord::Base.configurations['stoa'] = {:adapter => 'sqlite3', :database => db.path} 16 + ApplicationRecord.configurations['stoa'] = {:adapter => 'sqlite3', :database => db.path}
17 end 17 end
18 18
19 attr_accessor :person 19 attr_accessor :person
plugins/stoa/test/functional/stoa_plugin_controller_test.rb
@@ -9,7 +9,7 @@ class StoaPluginControllerTest &lt; ActionController::TestCase @@ -9,7 +9,7 @@ class StoaPluginControllerTest &lt; ActionController::TestCase
9 @controller = StoaPluginController.new 9 @controller = StoaPluginController.new
10 @request = ActionController::TestRequest.new 10 @request = ActionController::TestRequest.new
11 @response = ActionController::TestResponse.new 11 @response = ActionController::TestResponse.new
12 - ActiveRecord::Base.configurations['stoa'] = {:adapter => 'sqlite3', :database => ':memory:', :verbosity => 'quiet'} 12 + ApplicationRecord.configurations['stoa'] = {:adapter => 'sqlite3', :database => ':memory:', :verbosity => 'quiet'}
13 env = Environment.default 13 env = Environment.default
14 env.enable_plugin(StoaPlugin.name) 14 env.enable_plugin(StoaPlugin.name)
15 env.enable('skip_new_user_email_confirmation') 15 env.enable('skip_new_user_email_confirmation')
plugins/stoa/test/unit/usp_user_test.rb
@@ -5,15 +5,16 @@ class StoaPlugin::UspUserTest &lt; ActiveSupport::TestCase @@ -5,15 +5,16 @@ class StoaPlugin::UspUserTest &lt; ActiveSupport::TestCase
5 SALT=YAML::load(File.open(StoaPlugin.root_path + 'config.yml'))['salt'] 5 SALT=YAML::load(File.open(StoaPlugin.root_path + 'config.yml'))['salt']
6 6
7 @db = Tempfile.new('stoa-test') 7 @db = Tempfile.new('stoa-test')
8 - configs = ActiveRecord::Base.configurations['stoa'] = {:adapter => 'sqlite3', :database => @db.path}  
9 - ActiveRecord::Base.establish_connection(:stoa) 8 + configs = ApplicationRecord.configurations['stoa'] = {:adapter => 'sqlite3', :database => @db.path}
  9 + ApplicationRecord.establish_connection(:stoa)
10 ActiveRecord::Schema.verbose = false 10 ActiveRecord::Schema.verbose = false
11 ActiveRecord::Schema.create_table "pessoa" do |t| 11 ActiveRecord::Schema.create_table "pessoa" do |t|
12 t.integer "codpes" 12 t.integer "codpes"
13 t.text "numcpf" 13 t.text "numcpf"
14 t.date "dtanas" 14 t.date "dtanas"
15 end 15 end
16 - ActiveRecord::Base.establish_connection(:test) 16 + ApplicationRecord.establish_connection(:test)
  17 + StoaPlugin::UspUser.reset_column_information
17 18
18 def setup 19 def setup
19 StoaPlugin::UspUser.create({:codpes => 123456, :cpf => Digest::MD5.hexdigest(SALT+'12345678'), :birth_date => '1970-01-30'}, :without_protection => true) 20 StoaPlugin::UspUser.create({:codpes => 123456, :cpf => Digest::MD5.hexdigest(SALT+'12345678'), :birth_date => '1970-01-30'}, :without_protection => true)
plugins/sub_organizations/lib/sub_organizations_plugin/approve_paternity_relation.rb
1 -class SubOrganizationsPlugin::ApprovePaternityRelation < ActiveRecord::Base 1 +class SubOrganizationsPlugin::ApprovePaternityRelation < ApplicationRecord
2 2
3 belongs_to :task 3 belongs_to :task
4 belongs_to :parent, :polymorphic => true 4 belongs_to :parent, :polymorphic => true
plugins/sub_organizations/lib/sub_organizations_plugin/relation.rb
1 -class SubOrganizationsPlugin::Relation < ActiveRecord::Base 1 +class SubOrganizationsPlugin::Relation < ApplicationRecord
2 2
3 belongs_to :parent, :polymorphic => true 3 belongs_to :parent, :polymorphic => true
4 belongs_to :child, :polymorphic => true 4 belongs_to :child, :polymorphic => true
plugins/suppliers/db/migrate/20130704000000_create_suppliers_plugin_tables.rb
1 class CreateSuppliersPluginTables < ActiveRecord::Migration 1 class CreateSuppliersPluginTables < ActiveRecord::Migration
2 def self.up 2 def self.up
3 # check if distribution plugin already moved the table 3 # check if distribution plugin already moved the table
4 - return if ActiveRecord::Base.connection.table_exists? :suppliers_plugin_suppliers 4 + return if ApplicationRecord.connection.table_exists? :suppliers_plugin_suppliers
5 5
6 create_table :suppliers_plugin_suppliers do |t| 6 create_table :suppliers_plugin_suppliers do |t|
7 t.integer :profile_id 7 t.integer :profile_id
plugins/suppliers/db/migrate/20130704202336_create_suppliers_plugin_source_product.rb
1 class CreateSuppliersPluginSourceProduct < ActiveRecord::Migration 1 class CreateSuppliersPluginSourceProduct < ActiveRecord::Migration
2 def self.up 2 def self.up
3 # check if distribution plugin already moved the table 3 # check if distribution plugin already moved the table
4 - return if ActiveRecord::Base.connection.table_exists? "suppliers_plugin_source_products" 4 + return if ApplicationRecord.connection.table_exists? "suppliers_plugin_source_products"
5 5
6 create_table :suppliers_plugin_source_products do |t| 6 create_table :suppliers_plugin_source_products do |t|
7 t.integer "from_product_id" 7 t.integer "from_product_id"
plugins/suppliers/db/migrate/20130902115916_add_active_to_suppliers_plugin_supplier.rb
1 -class SuppliersPlugin::Supplier < ActiveRecord::Base 1 +class SuppliersPlugin::Supplier < ApplicationRecord
2 end 2 end
3 3
4 class AddActiveToSuppliersPluginSupplier < ActiveRecord::Migration 4 class AddActiveToSuppliersPluginSupplier < ActiveRecord::Migration
plugins/suppliers/lib/default_delegate.rb
@@ -126,4 +126,4 @@ module DefaultDelegate @@ -126,4 +126,4 @@ module DefaultDelegate
126 126
127 end 127 end
128 128
129 -ActiveRecord::Base.extend DefaultDelegate::ClassMethods 129 +ApplicationRecord.extend DefaultDelegate::ClassMethods
plugins/suppliers/models/suppliers_plugin/source_product.rb
1 -class SuppliersPlugin::SourceProduct < ActiveRecord::Base 1 +class SuppliersPlugin::SourceProduct < ApplicationRecord
2 2
3 attr_accessible :from_product, :to_product, :quantity 3 attr_accessible :from_product, :to_product, :quantity
4 4
plugins/suppliers/models/suppliers_plugin/supplier.rb
1 -class SuppliersPlugin::Supplier < ActiveRecord::Base 1 +class SuppliersPlugin::Supplier < ApplicationRecord
2 2
3 attr_accessor :distribute_products_on_create, :dont_destroy_dummy, :identifier_from_name 3 attr_accessor :distribute_products_on_create, :dont_destroy_dummy, :identifier_from_name
4 4
plugins/tolerance_time/lib/tolerance_time_plugin/publication.rb
1 -class ToleranceTimePlugin::Publication < ActiveRecord::Base 1 +class ToleranceTimePlugin::Publication < ApplicationRecord
2 2
3 belongs_to :target, :polymorphic => true 3 belongs_to :target, :polymorphic => true
4 validates_presence_of :target_id, :target_type 4 validates_presence_of :target_id, :target_type
plugins/tolerance_time/lib/tolerance_time_plugin/tolerance.rb
1 -class ToleranceTimePlugin::Tolerance < ActiveRecord::Base 1 +class ToleranceTimePlugin::Tolerance < ApplicationRecord
2 2
3 belongs_to :profile 3 belongs_to :profile
4 validates_presence_of :profile_id 4 validates_presence_of :profile_id
plugins/volunteers/models/volunteers_plugin/assignment.rb
1 -class VolunteersPlugin::Assignment < ActiveRecord::Base 1 +class VolunteersPlugin::Assignment < ApplicationRecord
2 2
3 attr_accessible :profile_id 3 attr_accessible :profile_id
4 4
plugins/volunteers/models/volunteers_plugin/period.rb
1 -class VolunteersPlugin::Period < ActiveRecord::Base 1 +class VolunteersPlugin::Period < ApplicationRecord
2 2
3 attr_accessible :name 3 attr_accessible :name
4 attr_accessible :start, :end 4 attr_accessible :start, :end
test/functional/role_controller_test.rb
@@ -80,7 +80,7 @@ class RoleControllerTest &lt; ActionController::TestCase @@ -80,7 +80,7 @@ class RoleControllerTest &lt; ActionController::TestCase
80 role = Role.create!(:name => 'environment_role', :key => 'environment_role', :environment => Environment.default) 80 role = Role.create!(:name => 'environment_role', :key => 'environment_role', :environment => Environment.default)
81 get :edit, :id => role.id 81 get :edit, :id => role.id
82 ['Environment', 'Profile'].each do |key| 82 ['Environment', 'Profile'].each do |key|
83 - ActiveRecord::Base::PERMISSIONS[key].each do |permission, value| 83 + ApplicationRecord::PERMISSIONS[key].each do |permission, value|
84 assert_select ".permissions.#{key.downcase} input##{permission}" 84 assert_select ".permissions.#{key.downcase} input##{permission}"
85 end 85 end
86 end 86 end
@@ -89,7 +89,7 @@ class RoleControllerTest &lt; ActionController::TestCase @@ -89,7 +89,7 @@ class RoleControllerTest &lt; ActionController::TestCase
89 should 'display permissions only for profile when editing a profile role' do 89 should 'display permissions only for profile when editing a profile role' do
90 role = Role.create!(:name => 'profile_role', :key => 'profile_role', :environment => Environment.default) 90 role = Role.create!(:name => 'profile_role', :key => 'profile_role', :environment => Environment.default)
91 get :edit, :id => role.id 91 get :edit, :id => role.id
92 - ActiveRecord::Base::PERMISSIONS['Profile'].each do |permission, value| 92 + ApplicationRecord::PERMISSIONS['Profile'].each do |permission, value|
93 assert_select "input##{permission}" 93 assert_select "input##{permission}"
94 end 94 end
95 assert_select ".permissions.environment", false 95 assert_select ".permissions.environment", false
test/integration/multi_tenancy_test.rb
@@ -29,12 +29,12 @@ class MultiTenancyTest &lt; ActionDispatch::IntegrationTest @@ -29,12 +29,12 @@ class MultiTenancyTest &lt; ActionDispatch::IntegrationTest
29 user = create_user 29 user = create_user
30 session_obj = create(Session, user_id: user.id, session_id: 'some_id', data: {}) 30 session_obj = create(Session, user_id: user.id, session_id: 'some_id', data: {})
31 person_identifier = user.person.identifier 31 person_identifier = user.person.identifier
32 - 32 +
33 Noosfero::MultiTenancy.setup!('schema1.com') 33 Noosfero::MultiTenancy.setup!('schema1.com')
34 host! 'schema2.com' 34 host! 'schema2.com'
35 cookies[:_noosfero_session] = session_obj.session_id 35 cookies[:_noosfero_session] = session_obj.session_id
36 assert_nothing_raised { get "/myprofile/#{person_identifier}" } 36 assert_nothing_raised { get "/myprofile/#{person_identifier}" }
37 - assert_equal 'public', ActiveRecord::Base.connection.schema_search_path 37 + assert_equal 'public', ApplicationRecord.connection.schema_search_path
38 end 38 end
39 39
40 end 40 end
test/mocks/test/environment.rb
1 require File.expand_path(File.dirname(__FILE__) + "/../../../app/models/environment") 1 require File.expand_path(File.dirname(__FILE__) + "/../../../app/models/environment")
2 2
3 -class Environment < ActiveRecord::Base 3 +class Environment < ApplicationRecord
4 def self.available_features 4 def self.available_features
5 { 5 {
6 'feature1' => 'Enable Feature 1', 6 'feature1' => 'Enable Feature 1',
test/support/factories.rb
@@ -5,9 +5,9 @@ module Noosfero::Factory @@ -5,9 +5,9 @@ module Noosfero::Factory
5 attrs[:slug] = attrs[:name].to_slug if attrs[:name].present? && attrs[:slug].blank? && defaults[:slug].present? 5 attrs[:slug] = attrs[:name].to_slug if attrs[:name].present? && attrs[:slug].blank? && defaults[:slug].present?
6 data = defaults_for(name.to_s.gsub('::','')).merge(attrs) 6 data = defaults_for(name.to_s.gsub('::','')).merge(attrs)
7 klass = name.to_s.camelize.constantize 7 klass = name.to_s.camelize.constantize
8 - if klass.superclass != ActiveRecord::Base  
9 - data[:type] = klass.to_s  
10 - end 8 +
  9 + data[:type] = klass.to_s if klass.column_names.include? 'type'
  10 +
11 if options[:timestamps] 11 if options[:timestamps]
12 fast_insert_with_timestamps(klass, data) 12 fast_insert_with_timestamps(klass, data)
13 else 13 else
@@ -129,7 +129,7 @@ module Noosfero::Factory @@ -129,7 +129,7 @@ module Noosfero::Factory
129 129
130 def fast_insert(klass, data) 130 def fast_insert(klass, data)
131 names = data.keys 131 names = data.keys
132 - values = names.map {|k| ActiveRecord::Base.send(:sanitize_sql_array, ['?', data[k]]) } 132 + values = names.map {|k| ApplicationRecord.send(:sanitize_sql_array, ['?', data[k]]) }
133 sql = 'insert into %s(%s) values (%s)' % [klass.table_name, names.join(','), values.join(',')] 133 sql = 'insert into %s(%s) values (%s)' % [klass.table_name, names.join(','), values.join(',')]
134 klass.connection.execute(sql) 134 klass.connection.execute(sql)
135 klass.order(:id).last 135 klass.order(:id).last
test/test_helper.rb
@@ -187,14 +187,14 @@ class ActiveSupport::TestCase @@ -187,14 +187,14 @@ class ActiveSupport::TestCase
187 end 187 end
188 188
189 def uses_postgresql(schema_name = 'test_schema') 189 def uses_postgresql(schema_name = 'test_schema')
190 - adapter = ActiveRecord::Base.connection.class 190 + adapter = ApplicationRecord.connection.class
191 adapter.any_instance.stubs(:adapter_name).returns('PostgreSQL') 191 adapter.any_instance.stubs(:adapter_name).returns('PostgreSQL')
192 adapter.any_instance.stubs(:schema_search_path).returns(schema_name) 192 adapter.any_instance.stubs(:schema_search_path).returns(schema_name)
193 Noosfero::MultiTenancy.stubs(:on?).returns(true) 193 Noosfero::MultiTenancy.stubs(:on?).returns(true)
194 end 194 end
195 195
196 def uses_sqlite 196 def uses_sqlite
197 - adapter = ActiveRecord::Base.connection.class 197 + adapter = ApplicationRecord.connection.class
198 adapter.any_instance.stubs(:adapter_name).returns('SQLite') 198 adapter.any_instance.stubs(:adapter_name).returns('SQLite')
199 Noosfero::MultiTenancy.stubs(:on?).returns(false) 199 Noosfero::MultiTenancy.stubs(:on?).returns(false)
200 end 200 end
test/unit/geo_ref_test.rb
@@ -22,7 +22,7 @@ class GeoRefTest &lt; ActiveSupport::TestCase @@ -22,7 +22,7 @@ class GeoRefTest &lt; ActiveSupport::TestCase
22 @acme = Enterprise.create! environment: env, identifier: 'acme', name: 'ACME', 22 @acme = Enterprise.create! environment: env, identifier: 'acme', name: 'ACME',
23 city: 'Salvador', state: 'Bahia', country: 'BR', lat: -12.9, lng: -38.5 23 city: 'Salvador', state: 'Bahia', country: 'BR', lat: -12.9, lng: -38.5
24 def sql_dist_to(ll) 24 def sql_dist_to(ll)
25 - ActiveRecord::Base.connection.execute( 25 + ApplicationRecord.connection.execute(
26 "SELECT #{Noosfero::GeoRef.sql_dist ll[0], ll[1]} as dist" + 26 "SELECT #{Noosfero::GeoRef.sql_dist ll[0], ll[1]} as dist" +
27 " FROM profiles WHERE id = #{@acme.id};" 27 " FROM profiles WHERE id = #{@acme.id};"
28 ).first['dist'].to_f.round 28 ).first['dist'].to_f.round
test/unit/multi_tenancy.rb
@@ -36,7 +36,7 @@ class MultiTenancyTest &lt; ActiveSupport::TestCase @@ -36,7 +36,7 @@ class MultiTenancyTest &lt; ActiveSupport::TestCase
36 36
37 def test_set_schema_by_host 37 def test_set_schema_by_host
38 Noosfero::MultiTenancy.expects(:mapping).returns({ 'host' => 'schema' }) 38 Noosfero::MultiTenancy.expects(:mapping).returns({ 'host' => 'schema' })
39 - adapter = ActiveRecord::Base.connection.class 39 + adapter = ApplicationRecord.connection.class
40 adapter.any_instance.expects(:schema_search_path=).with('schema').returns(true) 40 adapter.any_instance.expects(:schema_search_path=).with('schema').returns(true)
41 assert Noosfero::MultiTenancy.db_by_host = 'host' 41 assert Noosfero::MultiTenancy.db_by_host = 'host'
42 end 42 end
test/unit/sqlite_extension_test.rb
@@ -1,34 +0,0 @@ @@ -1,34 +0,0 @@
1 -require_relative "../test_helper"  
2 -  
3 -# if this test is run without SQLite (e.g. with mysql or postgres), the tests  
4 -# will just pass. The idea is to test our local extensions to SQLite.  
5 -class SQliteExtensionTest < ActiveSupport::TestCase  
6 -  
7 - if ActiveRecord::Base.connection.adapter_name =~ /^sqlite$/i  
8 -  
9 - should 'have power function' do  
10 - assert_in_delta 8.0, ActiveRecord::Base.connection.execute('select pow(2.0, 3.0) as result').first['result'], 0.0001  
11 - end  
12 -  
13 - should 'have radians function' do  
14 - assert_in_delta Math::PI/2, ActiveRecord::Base.connection.execute('select radians(90) as rad').first['rad'], 0.0001  
15 - end  
16 -  
17 - should 'have square root function' do  
18 - assert_in_delta 1.4142, ActiveRecord::Base.connection.execute('select sqrt(2) as sqrt').first['sqrt'], 0.0001  
19 - end  
20 -  
21 - should 'have a distance function' do  
22 - args = [32.918593, -96.958444, 32.951613, -96.958444].map{|l|l * Math::PI/180}  
23 - assert_in_delta 2.28402, ActiveRecord::Base.connection.execute("select spheric_distance(#{args.inspect[1..-2]}, 3963.19) as dist").first['dist'], 0.0001  
24 - end  
25 -  
26 - else  
27 -  
28 - should 'just pass (not using SQLite)' do  
29 - assert true  
30 - end  
31 -  
32 - end  
33 -  
34 -end