This project is archived and is in readonly mode.
self within AR scope evaluating to parent class instead of calling class
Reported by Sean | August 10th, 2010 @ 09:03 PM
I don't know if this is a bug or intentional, but when calling a :scope in a parent class from it's child class (STI model), self within the scope evaluates to the parent class.
According to standard ruby, it should evaluate to the class that called it, not the parent class.
Reproducible example:
class A < AR::Base
scope :test, lambda { puts self.to_s }
end
class B < A ; end
A.test
=> 'A'
B.test
=> 'A'
Comments and changes to this ticket
-
Sean August 10th, 2010 @ 09:04 PM
The reason this is a problem is that if you have scopes in a parent class that you're calling from a couple of different child classes, you may need to perform an action based on the class that called the scope.
-
Henrik Hodne August 11th, 2010 @ 01:12 AM
I can confirm that this is reproducible. However, I think this is due to Ruby evaluating self as you create the proc, and not when the proc is called. So, I think this is intentional, and at least not a rails problem.
This sortof does what AR::Base.scope() does, at least when it comes to defining methods.
module Kernel def singleton_class class << self self end end unless respond_to?(:singleton_class) end class A def self.define_scope(name, block) singleton_class.send(:define_method, name) do ret = block.call() ret end end define_scope(:test_two, lambda { self.to_s }) def to_s 'A' end end block = lambda { self.to_s } A.define_scope(:test_scopey, block) class B < A def to_s 'B' end end A.test_scopey # => "main" B.test_scopey # => "main" A.test_two # => "A" B.test_two # => "A"
-
Santiago Pastorino February 2nd, 2011 @ 05:00 PM
- State changed from new to open
This issue has been automatically marked as stale because it has not been commented on for at least three months.
The resources of the Rails core team are limited, and so we are asking for your help. If you can still reproduce this error on the 3-0-stable branch or on master, please reply with all of the information you have about it and add "[state:open]" to your comment. This will reopen the ticket for review. Likewise, if you feel that this is a very important feature for Rails to include, please reply with your explanation so we can consider it.
Thank you for all your contributions, and we hope you will understand this step to focus our efforts where they are most helpful.
-
Santiago Pastorino February 2nd, 2011 @ 05:00 PM
- State changed from open to stale
Create your profile
Help contribute to this project by taking a few moments to create your personal profile. Create your profile »
<h2 style="font-size: 14px">Tickets have moved to Github</h2>
The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>