DEV Community

mixbo
mixbo

Posted on

2 1

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 :)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

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 :)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️