DEV Community

mixbo
mixbo

Posted on

More readable string method in rails

Alt Text

First look at the code:

Rails.env.development? #=> true

Enter fullscreen mode Exit fullscreen mode

If rails run at local development environment it will return true

Why can call the development? method directly on the Rails.env object?

The point is that you can use ? suffix at method very simple, let's show you source code.

module ActiveSupport
  class StringInquirer < String
    def method_missing(method_name, *arguments)
      if method_name[-1] == "?"
        self == method_name[0..-2]
      else
        super
      end
    end
  end
end
Enter fullscreen mode Exit fullscreen mode

In fact Rails.env is anActiveSupport::StringInquirer instance object. the ActiveSupport::StringInquirer object extends the method_missing of the String class.

Mainly compare the string before ? with the string itself

name = ActiveSupport::StringInquirer.new("mixbo")
name.mixbo? #=>true

'mixbo?'[0..-2] #=> 'mixbo' 
'mixbo' == 'mixbo' #=>true
Enter fullscreen mode Exit fullscreen mode

Hope it can help you :)

Top comments (2)

Collapse
 
jsrn profile image
James

This is part of the "Rails magic" that I'd never bothered to dig into and learn how it actually works, so this was really cool to read, thank you.

Collapse
 
ihavecoke profile image
mixbo

keep learnning :)