ActiveSupport :: StringInquirer in Rails

I have a user model with a status column. Instead of doing string comparisons every time like this

user.status == 'verified' 

I though I had to do

 user.status.verified? 

So I added the following code

  def status ActiveSupport::StringInquirer.new(self.status) end 

But now I get the stack level too deep, which is understandable. How to fix it?

I am using Rails 3.2.

+4
source share
4 answers

Your problem is that you call status inside the status method, which causes a problem with infinite recursion.

Most of the answers here focus on using the ActiveSupport :: StringInquirer initializer, for example:

 def status return unless self['status'] ActiveSupport::StringInquirer.new(self['status']) end 

But you do not need it. ActiveSupport adds a query method for all rows, so you can do it this way:

 def status self['status'].try(:inquiry) end 

This is the same as using read_attribute :

 def status read_attribute(:status).try(:inquiry) end 

Or you can just call super:

 def status super.try(:inquiry) end 
+15
source

Use the following code to prevent a stack level error that is too deep:

 def status ActiveSupport::StringInquirer.new(self['status']) end 
+2
source

You might want to read the section “Overwriting Default Accessories” in ActiveRecord :: Basic Documentation: http://api.rubyonrails.org/classes/ActiveRecord/Base.html

Essentially, you will use read_attribute and write_attribute (or self ['attribute'], for example, Baldrick) to access the base attribute without calling the attribute access method.

+2
source

The accepted answer does not handle the case when the attribute is zero. This is better:

 def status (read_attribute(:status) || "").inquiry end 
0
source

Source: https://habr.com/ru/post/1389729/


All Articles