DEV Community

loading...

More readable string method in rails

ihavecoke profile image mixbo ・1 min read

Alt Text

First look at the code:

Rails.env.development? #=> true

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

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

Hope it can help you :)

Discussion (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 Author

keep learnning :)

Forem Open with the Forem app