Nick Vanderbilt Nick Vanderbilt - 4 months ago 15
Ruby Question

ActiveSupport::StringInquirer in Rails

I have a User model with status column. Rather than doing string comparison everytime like this

user.status == 'verified'


I though I should do

user.status.verified?


So I added following code

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


But now I am getting stack level too deep which is understandable. How do I fix this?

I am using Rails 3.2.

Answer

Your problem is that you're calling status inside the status method, which causes an infinite recursion problem.

Most answers here focus on using ActiveSupport::StringInquirer initializer, like this:

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

But you don't need it. ActiveSupport adds an inquiry method to all strings, so you can do it like that:

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