From c4d157aafe05dde4a19dff2d95165e4022627608 Mon Sep 17 00:00:00 2001 From: Alfred Dominic Date: Mon, 3 Dec 2018 15:22:59 +0530 Subject: [PATCH] option to disable scopes that `ActiveRecord.enum` generates by default --- activerecord/CHANGELOG.md | 4 ++++ activerecord/lib/active_record/enum.rb | 7 +++++-- activerecord/test/cases/enum_test.rb | 9 +++++++++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md index db291726e7..587831f1bb 100644 --- a/activerecord/CHANGELOG.md +++ b/activerecord/CHANGELOG.md @@ -1,3 +1,7 @@ +* Allow disabling scopes generated by `ActiveRecord.enum`. + + *Alfred Dominic* + * Ensure that `delete_all` on collection proxy returns affected count. *Ryuta Kamizono* diff --git a/activerecord/lib/active_record/enum.rb b/activerecord/lib/active_record/enum.rb index d62cd3f92a..d7cb7691e0 100644 --- a/activerecord/lib/active_record/enum.rb +++ b/activerecord/lib/active_record/enum.rb @@ -149,6 +149,7 @@ module ActiveRecord klass = self enum_prefix = definitions.delete(:_prefix) enum_suffix = definitions.delete(:_suffix) + enum_scopes = definitions.delete(:_scopes) definitions.each do |name, values| assert_valid_enum_definition_values(values) # statuses = { } @@ -195,8 +196,10 @@ module ActiveRecord define_method("#{value_method_name}!") { update!(attr => value) } # scope :active, -> { where(status: 0) } - klass.send(:detect_enum_conflict!, name, value_method_name, true) - klass.scope value_method_name, -> { where(attr => value) } + if enum_scopes != false + klass.send(:detect_enum_conflict!, name, value_method_name, true) + klass.scope value_method_name, -> { where(attr => value) } + end end end enum_values.freeze diff --git a/activerecord/test/cases/enum_test.rb b/activerecord/test/cases/enum_test.rb index fef06e6edd..8a0f6f6df1 100644 --- a/activerecord/test/cases/enum_test.rb +++ b/activerecord/test/cases/enum_test.rb @@ -551,4 +551,13 @@ class EnumTest < ActiveRecord::TestCase test "data type of Enum type" do assert_equal :integer, Book.type_for_attribute("status").type end + + test "scopes can be disabled" do + klass = Class.new(ActiveRecord::Base) do + self.table_name = "books" + enum status: [:proposed, :written], _scopes: false + end + + assert_raises(NoMethodError) { klass.proposed } + end end