aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--actionpack/CHANGELOG.md2
-rw-r--r--actionpack/lib/action_controller/metal/exceptions.rb5
-rw-r--r--actionpack/lib/action_dispatch/testing/assertions/selector.rb1
-rw-r--r--actionpack/test/controller/assert_select_test.rb7
-rw-r--r--activerecord/CHANGELOG.md10
-rw-r--r--activerecord/lib/active_record/associations/preloader/association.rb5
-rw-r--r--activerecord/lib/active_record/attribute_methods/read.rb5
-rw-r--r--activerecord/lib/active_record/locking/optimistic.rb31
-rw-r--r--activerecord/lib/active_record/nested_attributes.rb2
-rw-r--r--activerecord/lib/active_record/persistence.rb30
-rw-r--r--activerecord/lib/active_record/querying.rb1
-rw-r--r--activerecord/lib/active_record/relation/finder_methods.rb19
-rw-r--r--activerecord/test/cases/associations/eager_test.rb11
-rw-r--r--activerecord/test/cases/base_test.rb14
-rw-r--r--activerecord/test/cases/locking_test.rb16
-rw-r--r--activerecord/test/cases/nested_attributes_test.rb13
-rw-r--r--activerecord/test/cases/relations_test.rb34
-rw-r--r--activerecord/test/fixtures/peoples_treasures.yml3
-rw-r--r--activerecord/test/models/person.rb6
-rw-r--r--activerecord/test/schema/schema.rb6
-rw-r--r--activesupport/lib/active_support/cache/file_store.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/class/attribute_accessors.rb2
-rw-r--r--activesupport/lib/active_support/core_ext/module/attribute_accessors.rb2
-rw-r--r--activesupport/test/caching_test.rb10
-rw-r--r--activesupport/test/core_ext/class/attribute_accessor_test.rb14
-rw-r--r--activesupport/test/core_ext/module/attribute_accessor_test.rb14
-rw-r--r--guides/source/active_record_querying.textile70
-rw-r--r--railties/lib/rails/initializable.rb2
28 files changed, 273 insertions, 64 deletions
diff --git a/actionpack/CHANGELOG.md b/actionpack/CHANGELOG.md
index f004a4fce7..a4f5116a5d 100644
--- a/actionpack/CHANGELOG.md
+++ b/actionpack/CHANGELOG.md
@@ -1,5 +1,7 @@
## Rails 4.0.0 (unreleased) ##
+* Remove the leading \n added by textarea on assert_select. *Santiago Pastorino*
+
* Changed default value for `config.action_view.embed_authenticity_token_in_remote_forms`
to `false`. This change breaks remote forms that need to work also without javascript,
so if you need such behavior, you can either set it to `true` or explicitly pass
diff --git a/actionpack/lib/action_controller/metal/exceptions.rb b/actionpack/lib/action_controller/metal/exceptions.rb
index ece9ba3725..9a9db0fe5f 100644
--- a/actionpack/lib/action_controller/metal/exceptions.rb
+++ b/actionpack/lib/action_controller/metal/exceptions.rb
@@ -14,8 +14,6 @@ module ActionController
end
class MethodNotAllowed < ActionControllerError #:nodoc:
- attr_reader :allowed_methods
-
def initialize(*allowed_methods)
super("Only #{allowed_methods.to_sentence(:locale => :en)} requests are allowed.")
end
@@ -30,9 +28,6 @@ module ActionController
class MissingFile < ActionControllerError #:nodoc:
end
- class RenderError < ActionControllerError #:nodoc:
- end
-
class SessionOverflowError < ActionControllerError #:nodoc:
DEFAULT_MESSAGE = 'Your session data is larger than the data column in which it is to be stored. You must increase the size of your data column if you intend to store large data.'
diff --git a/actionpack/lib/action_dispatch/testing/assertions/selector.rb b/actionpack/lib/action_dispatch/testing/assertions/selector.rb
index 8eed85bce2..ea1ed20f3c 100644
--- a/actionpack/lib/action_dispatch/testing/assertions/selector.rb
+++ b/actionpack/lib/action_dispatch/testing/assertions/selector.rb
@@ -269,6 +269,7 @@ module ActionDispatch
end
end
text.strip! unless NO_STRIP.include?(match.name)
+ text.sub!(/\A\n/, '') if match.name == "textarea"
unless match_with.is_a?(Regexp) ? (text =~ match_with) : (text == match_with.to_s)
content_mismatch ||= sprintf("<%s> expected but was\n<%s>.", match_with, text)
true
diff --git a/actionpack/test/controller/assert_select_test.rb b/actionpack/test/controller/assert_select_test.rb
index d3359e79a6..3d667f0a2f 100644
--- a/actionpack/test/controller/assert_select_test.rb
+++ b/actionpack/test/controller/assert_select_test.rb
@@ -131,6 +131,13 @@ class AssertSelectTest < ActionController::TestCase
assert_raise(Assertion) { assert_select "pre", :html=>text }
end
+ def test_strip_textarea
+ render_html %Q{<textarea>\n\nfoo\n</textarea>}
+ assert_select "textarea", "\nfoo\n"
+ render_html %Q{<textarea>\nfoo</textarea>}
+ assert_select "textarea", "foo"
+ end
+
def test_counts
render_html %Q{<div id="1">foo</div><div id="2">foo</div>}
assert_nothing_raised { assert_select "div", 2 }
diff --git a/activerecord/CHANGELOG.md b/activerecord/CHANGELOG.md
index 1d5b8841e2..26f6093bc2 100644
--- a/activerecord/CHANGELOG.md
+++ b/activerecord/CHANGELOG.md
@@ -1,5 +1,15 @@
## Rails 4.0.0 (unreleased) ##
+* Added `#find_by` and `#find_by!` to mirror the functionality
+ provided by dynamic finders in a way that allows dynamic input more
+ easily:
+
+ Post.find_by name: 'Spartacus', rating: 4
+ Post.find_by "published_at < ?", 2.weeks.ago
+ Post.find_by! name: 'Spartacus'
+
+ *Jon Leighton*
+
* Added ActiveRecord::Base#slice to return a hash of the given methods with
their names as keys and returned values as values.
diff --git a/activerecord/lib/active_record/associations/preloader/association.rb b/activerecord/lib/active_record/associations/preloader/association.rb
index 253998fb23..b4c3908b10 100644
--- a/activerecord/lib/active_record/associations/preloader/association.rb
+++ b/activerecord/lib/active_record/associations/preloader/association.rb
@@ -77,7 +77,7 @@ module ActiveRecord
# Some databases impose a limit on the number of ids in a list (in Oracle it's 1000)
# Make several smaller queries if necessary or make one query if the adapter supports it
sliced = owner_keys.each_slice(model.connection.in_clause_length || owner_keys.size)
- records = sliced.map { |slice| records_for(slice) }.flatten
+ records = sliced.map { |slice| records_for(slice).to_a }.flatten
end
# Each record may have multiple owners, and vice-versa
@@ -93,7 +93,8 @@ module ActiveRecord
end
def build_scope
- scope = klass.scoped
+ scope = klass.unscoped
+ scope.default_scoped = true
scope = scope.where(interpolate(options[:conditions]))
scope = scope.where(interpolate(preload_options[:conditions]))
diff --git a/activerecord/lib/active_record/attribute_methods/read.rb b/activerecord/lib/active_record/attribute_methods/read.rb
index d108de385f..dcc3d79de9 100644
--- a/activerecord/lib/active_record/attribute_methods/read.rb
+++ b/activerecord/lib/active_record/attribute_methods/read.rb
@@ -67,9 +67,8 @@ module ActiveRecord
@attributes_cache.fetch(attr_name.to_s) { |name|
column = @columns_hash.fetch(name) {
return @attributes.fetch(name) {
- if name == 'id'
- primary_key = self.class.primary_key
- @columns_hash[primary_key].type_cast(@attributes[primary_key])
+ if name == 'id' && self.class.primary_key != name
+ read_attribute(self.class.primary_key)
end
}
}
diff --git a/activerecord/lib/active_record/locking/optimistic.rb b/activerecord/lib/active_record/locking/optimistic.rb
index 8266427b71..a3412582fa 100644
--- a/activerecord/lib/active_record/locking/optimistic.rb
+++ b/activerecord/lib/active_record/locking/optimistic.rb
@@ -101,24 +101,29 @@ module ActiveRecord
end
end
- def destroy #:nodoc:
- return super unless locking_enabled?
+ def destroy_row
+ affected_rows = super
- if persisted?
- table = self.class.arel_table
- lock_col = self.class.locking_column
- predicate = table[self.class.primary_key].eq(id).
- and(table[lock_col].eq(send(lock_col).to_i))
+ if locking_enabled? && affected_rows != 1
+ raise ActiveRecord::StaleObjectError.new(self, "destroy")
+ end
- affected_rows = self.class.unscoped.where(predicate).delete_all
+ affected_rows
+ end
- unless affected_rows == 1
- raise ActiveRecord::StaleObjectError.new(self, "destroy")
- end
+ def relation_for_destroy
+ relation = super
+
+ if locking_enabled?
+ column_name = self.class.locking_column
+ column = self.class.columns_hash[column_name]
+ substitute = connection.substitute_at(column, relation.bind_values.length)
+
+ relation = relation.where(self.class.arel_table[column_name].eq(substitute))
+ relation.bind_values << [column, self[column_name].to_i]
end
- @destroyed = true
- freeze
+ relation
end
module ClassMethods
diff --git a/activerecord/lib/active_record/nested_attributes.rb b/activerecord/lib/active_record/nested_attributes.rb
index 6bf0becad8..32a1dae6bc 100644
--- a/activerecord/lib/active_record/nested_attributes.rb
+++ b/activerecord/lib/active_record/nested_attributes.rb
@@ -288,7 +288,7 @@ module ActiveRecord
# def pirate_attributes=(attributes)
# assign_nested_attributes_for_one_to_one_association(:pirate, attributes, mass_assignment_options)
# end
- class_eval <<-eoruby, __FILE__, __LINE__ + 1
+ generated_feature_methods.module_eval <<-eoruby, __FILE__, __LINE__ + 1
if method_defined?(:#{association_name}_attributes=)
remove_method(:#{association_name}_attributes=)
end
diff --git a/activerecord/lib/active_record/persistence.rb b/activerecord/lib/active_record/persistence.rb
index 35c922e979..bb504ae90f 100644
--- a/activerecord/lib/active_record/persistence.rb
+++ b/activerecord/lib/active_record/persistence.rb
@@ -124,19 +124,7 @@ module ActiveRecord
# that no changes should be made (since they can't be persisted).
def destroy
destroy_associations
-
- if persisted?
- pk = self.class.primary_key
- column = self.class.columns_hash[pk]
- substitute = connection.substitute_at(column, 0)
-
- relation = self.class.unscoped.where(
- self.class.arel_table[pk].eq(substitute))
-
- relation.bind_values = [[column, id]]
- relation.delete_all
- end
-
+ destroy_row if persisted?
@destroyed = true
freeze
end
@@ -335,6 +323,22 @@ module ActiveRecord
def destroy_associations
end
+ def destroy_row
+ relation_for_destroy.delete_all
+ end
+
+ def relation_for_destroy
+ pk = self.class.primary_key
+ column = self.class.columns_hash[pk]
+ substitute = connection.substitute_at(column, 0)
+
+ relation = self.class.unscoped.where(
+ self.class.arel_table[pk].eq(substitute))
+
+ relation.bind_values = [[column, id]]
+ relation
+ end
+
def create_or_update
raise ReadOnlyRecord if readonly?
result = new_record? ? create : update
diff --git a/activerecord/lib/active_record/querying.rb b/activerecord/lib/active_record/querying.rb
index 0e6fecbc4b..95565b503a 100644
--- a/activerecord/lib/active_record/querying.rb
+++ b/activerecord/lib/active_record/querying.rb
@@ -5,6 +5,7 @@ module ActiveRecord
module Querying
delegate :find, :first, :first!, :last, :last!, :all, :exists?, :any?, :many?, :to => :scoped
delegate :first_or_create, :first_or_create!, :first_or_initialize, :to => :scoped
+ delegate :find_by, :find_by!, :to => :scoped
delegate :destroy, :destroy_all, :delete, :delete_all, :update, :update_all, :to => :scoped
delegate :find_each, :find_in_batches, :to => :scoped
delegate :select, :group, :order, :except, :reorder, :limit, :offset, :joins,
diff --git a/activerecord/lib/active_record/relation/finder_methods.rb b/activerecord/lib/active_record/relation/finder_methods.rb
index 2c74f4011d..74f8e30404 100644
--- a/activerecord/lib/active_record/relation/finder_methods.rb
+++ b/activerecord/lib/active_record/relation/finder_methods.rb
@@ -109,6 +109,25 @@ module ActiveRecord
end
end
+ # Finds the first record matching the specified conditions. There
+ # is no implied ording so if order matters, you should specify it
+ # yourself.
+ #
+ # If no record is found, returns <tt>nil</tt>.
+ #
+ # Post.find_by name: 'Spartacus', rating: 4
+ # Post.find_by "published_at < ?", 2.weeks.ago
+ #
+ def find_by(*args)
+ where(*args).first
+ end
+
+ # Like <tt>find_by</tt>, except that if no record is found, raises
+ # an <tt>ActiveRecord::RecordNotFound</tt> error.
+ def find_by!(*args)
+ where(*args).first!
+ end
+
# A convenience wrapper for <tt>find(:first, *args)</tt>. You can pass in all the
# same arguments to this method as you can to <tt>find(:first)</tt>.
def first(*args)
diff --git a/activerecord/test/cases/associations/eager_test.rb b/activerecord/test/cases/associations/eager_test.rb
index b27a93f857..efdb7cbb36 100644
--- a/activerecord/test/cases/associations/eager_test.rb
+++ b/activerecord/test/cases/associations/eager_test.rb
@@ -1169,4 +1169,15 @@ class EagerAssociationTest < ActiveRecord::TestCase
assert_no_queries { assert_equal 1, posts[0].categories[1].categorizations.length }
assert_no_queries { assert_equal 2, posts[1].categories[0].categorizations.length }
end
+
+ test "scoping with a circular preload" do
+ assert_equal Comment.find(1), Comment.preload(:post => :comments).scoping { Comment.find(1) }
+ end
+
+ test "preload ignores the scoping" do
+ assert_equal(
+ Comment.find(1).post,
+ Post.where('1 = 0').scoping { Comment.preload(:post).find(1).post }
+ )
+ end
end
diff --git a/activerecord/test/cases/base_test.rb b/activerecord/test/cases/base_test.rb
index f0fbca190c..5fb49d540f 100644
--- a/activerecord/test/cases/base_test.rb
+++ b/activerecord/test/cases/base_test.rb
@@ -2069,4 +2069,18 @@ class BasicsTest < ActiveRecord::TestCase
assert_nil hash[:firm_name]
assert_nil hash['firm_name']
end
+
+ ["find_by", "find_by!"].each do |meth|
+ test "#{meth} delegates to scoped" do
+ record = stub
+
+ scope = mock
+ scope.expects(meth).with(:foo, :bar).returns(record)
+
+ klass = Class.new(ActiveRecord::Base)
+ klass.stubs(:scoped => scope)
+
+ assert_equal record, klass.public_send(meth, :foo, :bar)
+ end
+ end
end
diff --git a/activerecord/test/cases/locking_test.rb b/activerecord/test/cases/locking_test.rb
index 807274ca67..cc6baa6153 100644
--- a/activerecord/test/cases/locking_test.rb
+++ b/activerecord/test/cases/locking_test.rb
@@ -9,6 +9,7 @@ require 'models/string_key_object'
require 'models/car'
require 'models/engine'
require 'models/wheel'
+require 'models/treasure'
class LockWithoutDefault < ActiveRecord::Base; end
@@ -22,7 +23,7 @@ class ReadonlyFirstNamePerson < Person
end
class OptimisticLockingTest < ActiveRecord::TestCase
- fixtures :people, :legacy_things, :references, :string_key_objects
+ fixtures :people, :legacy_things, :references, :string_key_objects, :peoples_treasures
def test_non_integer_lock_existing
s1 = StringKeyObject.find("record1")
@@ -230,15 +231,24 @@ class OptimisticLockingTest < ActiveRecord::TestCase
def test_polymorphic_destroy_with_dependencies_and_lock_version
car = Car.create!
-
+
assert_difference 'car.wheels.count' do
car.wheels << Wheel.create!
- end
+ end
assert_difference 'car.wheels.count', -1 do
car.destroy
end
assert car.destroyed?
end
+
+ def test_removing_has_and_belongs_to_many_associations_upon_destroy
+ p = RichPerson.create! first_name: 'Jon'
+ p.treasures.create!
+ assert !p.treasures.empty?
+ p.destroy
+ assert p.treasures.empty?
+ assert RichPerson.connection.select_all("SELECT * FROM peoples_treasures WHERE rich_person_id = 1").empty?
+ end
end
class OptimisticLockingWithSchemaChangeTest < ActiveRecord::TestCase
diff --git a/activerecord/test/cases/nested_attributes_test.rb b/activerecord/test/cases/nested_attributes_test.rb
index 09276a034e..0559bbbe9a 100644
--- a/activerecord/test/cases/nested_attributes_test.rb
+++ b/activerecord/test/cases/nested_attributes_test.rb
@@ -172,6 +172,19 @@ class TestNestedAttributesInGeneral < ActiveRecord::TestCase
man.interests_attributes = [{:id => interest.id, :topic => 'gardening'}]
assert_equal man.interests.first.topic, man.interests[0].topic
end
+
+ def test_allows_class_to_override_setter_and_call_super
+ mean_pirate_class = Class.new(Pirate) do
+ accepts_nested_attributes_for :parrot
+ def parrot_attributes=(attrs)
+ super(attrs.merge(:color => "blue"))
+ end
+ end
+ mean_pirate = mean_pirate_class.new
+ mean_pirate.parrot_attributes = { :name => "James" }
+ assert_equal "James", mean_pirate.parrot.name
+ assert_equal "blue", mean_pirate.parrot.color
+ end
end
class TestNestedAttributesOnAHasOneAssociation < ActiveRecord::TestCase
diff --git a/activerecord/test/cases/relations_test.rb b/activerecord/test/cases/relations_test.rb
index 3edc237c44..25eb7c1672 100644
--- a/activerecord/test/cases/relations_test.rb
+++ b/activerecord/test/cases/relations_test.rb
@@ -1256,4 +1256,38 @@ class RelationTest < ActiveRecord::TestCase
assert topics.loaded?
end
+
+ test "find_by with hash conditions returns the first matching record" do
+ assert_equal posts(:eager_other), Post.order(:id).find_by(author_id: 2)
+ end
+
+ test "find_by with non-hash conditions returns the first matching record" do
+ assert_equal posts(:eager_other), Post.order(:id).find_by("author_id = 2")
+ end
+
+ test "find_by with multi-arg conditions returns the first matching record" do
+ assert_equal posts(:eager_other), Post.order(:id).find_by('author_id = ?', 2)
+ end
+
+ test "find_by returns nil if the record is missing" do
+ assert_equal nil, Post.scoped.find_by("1 = 0")
+ end
+
+ test "find_by! with hash conditions returns the first matching record" do
+ assert_equal posts(:eager_other), Post.order(:id).find_by!(author_id: 2)
+ end
+
+ test "find_by! with non-hash conditions returns the first matching record" do
+ assert_equal posts(:eager_other), Post.order(:id).find_by!("author_id = 2")
+ end
+
+ test "find_by! with multi-arg conditions returns the first matching record" do
+ assert_equal posts(:eager_other), Post.order(:id).find_by!('author_id = ?', 2)
+ end
+
+ test "find_by! raises RecordNotFound if the record is missing" do
+ assert_raises(ActiveRecord::RecordNotFound) do
+ Post.scoped.find_by!("1 = 0")
+ end
+ end
end
diff --git a/activerecord/test/fixtures/peoples_treasures.yml b/activerecord/test/fixtures/peoples_treasures.yml
new file mode 100644
index 0000000000..a72b190d0c
--- /dev/null
+++ b/activerecord/test/fixtures/peoples_treasures.yml
@@ -0,0 +1,3 @@
+michael_diamond:
+ rich_person_id: <%= ActiveRecord::Fixtures.identify(:michael) %>
+ treasure_id: <%= ActiveRecord::Fixtures.identify(:diamond) %>
diff --git a/activerecord/test/models/person.rb b/activerecord/test/models/person.rb
index b7d5dabc4f..d5c0b351aa 100644
--- a/activerecord/test/models/person.rb
+++ b/activerecord/test/models/person.rb
@@ -85,3 +85,9 @@ class TightPerson < ActiveRecord::Base
end
class TightDescendant < TightPerson; end
+
+class RichPerson < ActiveRecord::Base
+ self.table_name = 'people'
+
+ has_and_belongs_to_many :treasures, :join_table => 'peoples_treasures'
+end
diff --git a/activerecord/test/schema/schema.rb b/activerecord/test/schema/schema.rb
index 5e7985c530..377fde5c96 100644
--- a/activerecord/test/schema/schema.rb
+++ b/activerecord/test/schema/schema.rb
@@ -439,6 +439,7 @@ ActiveRecord::Schema.define do
create_table :parrots, :force => true do |t|
t.column :name, :string
+ t.column :color, :string
t.column :parrot_sti_class, :string
t.column :killer_id, :integer
t.column :created_at, :datetime
@@ -469,6 +470,11 @@ ActiveRecord::Schema.define do
t.timestamps
end
+ create_table :peoples_treasures, :id => false, :force => true do |t|
+ t.column :rich_person_id, :integer
+ t.column :treasure_id, :integer
+ end
+
create_table :pets, :primary_key => :pet_id ,:force => true do |t|
t.string :name
t.integer :owner_id, :integer
diff --git a/activesupport/lib/active_support/cache/file_store.rb b/activesupport/lib/active_support/cache/file_store.rb
index b7712a4a15..8e6a3bc5a8 100644
--- a/activesupport/lib/active_support/cache/file_store.rb
+++ b/activesupport/lib/active_support/cache/file_store.rb
@@ -13,7 +13,7 @@ module ActiveSupport
attr_reader :cache_path
DIR_FORMATTER = "%03X"
- FILENAME_MAX_SIZE = 230 # max filename size on file system is 255, minus room for timestamp and random characters appended by Tempfile (used by atomic write)
+ FILENAME_MAX_SIZE = 228 # max filename size on file system is 255, minus room for timestamp and random characters appended by Tempfile (used by atomic write)
EXCLUDED_DIRS = ['.', '..'].freeze
def initialize(cache_path, options = nil)
diff --git a/activesupport/lib/active_support/core_ext/class/attribute_accessors.rb b/activesupport/lib/active_support/core_ext/class/attribute_accessors.rb
index 268303aaf2..95eb94fdf6 100644
--- a/activesupport/lib/active_support/core_ext/class/attribute_accessors.rb
+++ b/activesupport/lib/active_support/core_ext/class/attribute_accessors.rb
@@ -29,6 +29,7 @@ class Class
def cattr_reader(*syms)
options = syms.extract_options!
syms.each do |sym|
+ raise NameError.new("invalid attribute name") unless sym =~ /^[_A-Za-z]\w*$/
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
unless defined? @@#{sym}
@@#{sym} = nil
@@ -52,6 +53,7 @@ class Class
def cattr_writer(*syms)
options = syms.extract_options!
syms.each do |sym|
+ raise NameError.new("invalid attribute name") unless sym =~ /^[_A-Za-z]\w*$/
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
unless defined? @@#{sym}
@@#{sym} = nil
diff --git a/activesupport/lib/active_support/core_ext/module/attribute_accessors.rb b/activesupport/lib/active_support/core_ext/module/attribute_accessors.rb
index be94ae1565..84acb629ad 100644
--- a/activesupport/lib/active_support/core_ext/module/attribute_accessors.rb
+++ b/activesupport/lib/active_support/core_ext/module/attribute_accessors.rb
@@ -4,6 +4,7 @@ class Module
def mattr_reader(*syms)
options = syms.extract_options!
syms.each do |sym|
+ raise NameError.new("invalid attribute name") unless sym =~ /^[_A-Za-z]\w*$/
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
@@#{sym} = nil unless defined? @@#{sym}
@@ -25,6 +26,7 @@ class Module
def mattr_writer(*syms)
options = syms.extract_options!
syms.each do |sym|
+ raise NameError.new("invalid attribute name") unless sym =~ /^[_A-Za-z]\w*$/
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
def self.#{sym}=(obj)
@@#{sym} = obj
diff --git a/activesupport/test/caching_test.rb b/activesupport/test/caching_test.rb
index ba027f1ff0..4371a02934 100644
--- a/activesupport/test/caching_test.rb
+++ b/activesupport/test/caching_test.rb
@@ -579,6 +579,16 @@ class FileStoreTest < ActiveSupport::TestCase
assert_equal "views/index?id=1", @cache_with_pathname.send(:file_path_key, key)
end
+ # Test that generated cache keys are short enough to have Tempfile stuff added to them and
+ # remain valid
+ def test_filename_max_size
+ key = "#{'A' * ActiveSupport::Cache::FileStore::FILENAME_MAX_SIZE}"
+ path = @cache.send(:key_file_path, key)
+ Dir::Tmpname.create(path) do |tmpname, n, opts|
+ assert (File.basename(tmpname+'.lock').length <= 255), "Temp filename too long: #{File.basename(tmpname+'.lock').length}"
+ end
+ end
+
# Because file systems have a maximum filename size, filenames > max size should be split in to directories
# If filename is 'AAAAB', where max size is 4, the returned path should be AAAA/B
def test_key_transformation_max_filename_size
diff --git a/activesupport/test/core_ext/class/attribute_accessor_test.rb b/activesupport/test/core_ext/class/attribute_accessor_test.rb
index 3822e7af66..8d827f054e 100644
--- a/activesupport/test/core_ext/class/attribute_accessor_test.rb
+++ b/activesupport/test/core_ext/class/attribute_accessor_test.rb
@@ -42,4 +42,18 @@ class ClassAttributeAccessorTest < ActiveSupport::TestCase
assert !@object.respond_to?(:camp)
assert !@object.respond_to?(:camp=)
end
+
+ def test_should_raise_name_error_if_attribute_name_is_invalid
+ assert_raises NameError do
+ Class.new do
+ cattr_reader "invalid attribute name"
+ end
+ end
+
+ assert_raises NameError do
+ Class.new do
+ cattr_writer "invalid attribute name"
+ end
+ end
+ end
end
diff --git a/activesupport/test/core_ext/module/attribute_accessor_test.rb b/activesupport/test/core_ext/module/attribute_accessor_test.rb
index 6a2ad2f241..a577f90bdd 100644
--- a/activesupport/test/core_ext/module/attribute_accessor_test.rb
+++ b/activesupport/test/core_ext/module/attribute_accessor_test.rb
@@ -44,4 +44,18 @@ class ModuleAttributeAccessorTest < ActiveSupport::TestCase
assert !@object.respond_to?(:camp)
assert !@object.respond_to?(:camp=)
end
+
+ def test_should_raise_name_error_if_attribute_name_is_invalid
+ assert_raises NameError do
+ Class.new do
+ mattr_reader "invalid attribute name"
+ end
+ end
+
+ assert_raises NameError do
+ Class.new do
+ mattr_writer "invalid attribute name"
+ end
+ end
+ end
end
diff --git a/guides/source/active_record_querying.textile b/guides/source/active_record_querying.textile
index 8e23a577e2..14d0ba9b28 100644
--- a/guides/source/active_record_querying.textile
+++ b/guides/source/active_record_querying.textile
@@ -133,6 +133,24 @@ SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
<tt>Model.last</tt> returns +nil+ if no matching record is found. No exception will be raised.
+h5. +find_by+
+
+<tt>Model.find_by</tt> finds the first record matching some conditions. For example:
+
+<ruby>
+Client.find_by first_name: 'Lifo'
+# => #<Client id: 1, first_name: "Lifo">
+
+Client.find_by first_name: 'Jon'
+# => nil
+</ruby>
+
+It is equivalent to writing:
+
+<ruby>
+Client.where(first_name: 'Lifo').first
+</ruby>
+
h5(#first_1). +first!+
<tt>Model.first!</tt> finds the first record. For example:
@@ -167,6 +185,24 @@ SELECT * FROM clients ORDER BY clients.id DESC LIMIT 1
<tt>Model.last!</tt> raises +RecordNotFound+ if no matching record is found.
+h5(#find_by_1). +find_by!+
+
+<tt>Model.find_by!</tt> finds the first record matching some conditions. It raises +RecordNotFound+ if no matching record is found. For example:
+
+<ruby>
+Client.find_by! first_name: 'Lifo'
+# => #<Client id: 1, first_name: "Lifo">
+
+Client.find_by! first_name: 'Jon'
+# => RecordNotFound
+</ruby>
+
+It is equivalent to writing:
+
+<ruby>
+Client.where(first_name: 'Lifo').first!
+</ruby>
+
h4. Retrieving Multiple Objects
h5. Using Multiple Primary Keys
@@ -943,21 +979,23 @@ If, in the case of this +includes+ query, there were no comments for any posts,
h3. Scopes
-Scoping allows you to specify commonly-used ARel queries which can be referenced as method calls on the association objects or models. With these scopes, you can use every method previously covered such as +where+, +joins+ and +includes+. All scope methods will return an +ActiveRecord::Relation+ object which will allow for further methods (such as other scopes) to be called on it.
+Scoping allows you to specify commonly-used queries which can be referenced as method calls on the association objects or models. With these scopes, you can use every method previously covered such as +where+, +joins+ and +includes+. All scope methods will return an +ActiveRecord::Relation+ object which will allow for further methods (such as other scopes) to be called on it.
-To define a simple scope, we use the +scope+ method inside the class, passing the ARel query that we'd like run when this scope is called:
+To define a simple scope, we use the +scope+ method inside the class, passing the query that we'd like run when this scope is called:
<ruby>
class Post < ActiveRecord::Base
- scope :published, where(:published => true)
+ scope :published, -> { where(published: true) }
end
</ruby>
-Just like before, these methods are also chainable:
+This is exactly the same as defining a class method, and which you use is a matter of personal preference:
<ruby>
class Post < ActiveRecord::Base
- scope :published, where(:published => true).joins(:category)
+ def self.published
+ where(published: true)
+ end
end
</ruby>
@@ -965,8 +1003,8 @@ Scopes are also chainable within scopes:
<ruby>
class Post < ActiveRecord::Base
- scope :published, where(:published => true)
- scope :published_and_commented, published.and(self.arel_table[:comments_count].gt(0))
+ scope :published, -> { where(:published => true) }
+ scope :published_and_commented, -> { published.and(self.arel_table[:comments_count].gt(0)) }
end
</ruby>
@@ -983,25 +1021,13 @@ category = Category.first
category.posts.published # => [published posts belonging to this category]
</ruby>
-h4. Working with times
-
-If you're working with dates or times within scopes, due to how they are evaluated, you will need to use a lambda so that the scope is evaluated every time.
-
-<ruby>
-class Post < ActiveRecord::Base
- scope :created_before_now, lambda { where("created_at < ?", Time.zone.now ) }
-end
-</ruby>
-
-Without the +lambda+, this +Time.zone.now+ will only be called once.
-
h4. Passing in arguments
-When a +lambda+ is used for a +scope+, it can take arguments:
+Your scope can take arguments:
<ruby>
class Post < ActiveRecord::Base
- scope :created_before, lambda { |time| where("created_at < ?", time) }
+ scope :created_before, ->(time) { where("created_at < ?", time) }
end
</ruby>
@@ -1048,7 +1074,7 @@ If we wish for a scope to be applied across all queries to the model we can use
<ruby>
class Client < ActiveRecord::Base
- default_scope where("removed_at IS NULL")
+ default_scope { where("removed_at IS NULL") }
end
</ruby>
diff --git a/railties/lib/rails/initializable.rb b/railties/lib/rails/initializable.rb
index 04d5b55c69..a61673fab8 100644
--- a/railties/lib/rails/initializable.rb
+++ b/railties/lib/rails/initializable.rb
@@ -51,7 +51,7 @@ module Rails
def run_initializers(group=:default, *args)
return if instance_variable_defined?(:@ran)
- initializers.tsort.each do |initializer|
+ initializers.tsort_each do |initializer|
initializer.run(*args) if initializer.belongs_to?(group)
end
@ran = true