Permalink
Browse files

Only call :read_attribute once from #safe_send

This prevents calling read_attribute once for every column in the table when searching for the attribute thereby reducing calls to expensive methods like generated_external_attribute_methods
  • Loading branch information...
1 parent d81b6b0 commit 788196435f9f641a3771672ff4f87a4215b8d885 @christophermanning christophermanning committed with Jul 1, 2012
Showing with 17 additions and 1 deletion.
  1. +1 −1 config/initializers/active_record_extensions.rb
  2. +16 −0 spec/unit/active_record_extension_spec.rb
@@ -9,7 +9,7 @@ def rails_admin_default_object_label_method
end
def safe_send(value)
- if self.attributes.find{ |k,v| k.to_s == value.to_s }
+ if self.has_attribute?(value)
self.read_attribute(value)
else
self.send(value)
@@ -0,0 +1,16 @@
+require 'spec_helper'
+require File.expand_path('../../../config/initializers/active_record_extensions', __FILE__)
+
+describe 'ActiveRecord::Base', :active_record => true do
+ describe '#safe_send' do
+ it "only calls #read_attribute once" do
+ @player = Player.new
+ @player.number = 23
+ original_method = @player.method(:read_attribute)
+ @player.should_receive(:read_attribute).exactly(1).times do |*args|
+ original_method.call(*args)
+ end
+ @player.safe_send(:number).should == 23
+ end
+ end
+end

0 comments on commit 7881964

Please sign in to comment.