Kermit
Kermit

Reputation: 5982

Rails proper way to distinguish methods from variable names?

Now that my controllers are expanding beyond the basic REST actions it can get somewhat confusing as to whether a given expression is either a built in method, a controller method, from the model, or a variable.

Would adding empty parentheses to my controller methods when I call them from other methods cause any problems down the road? Like so:

if customer.save?
  subscription_checker()
end

I'm at least trying to always use an underscore in the names of the methods I create in order to make them look different from most of the built in methods.

Upvotes: 0

Views: 86

Answers (1)

Tom Lord
Tom Lord

Reputation: 28285

Would adding empty parentheses to my controller methods when I call them from other methods cause any problems down the road?

This is a valid way to distinguish between variables vs methods in ruby, but "You're Doing It Wrong" ™

Part of the ruby paradigm is that you shouldn't typically care whether the thing you're referencing is a variable or a method. This makes the code easier to read and refactor; keeping the developer's attention focused on code's intent rather than its implementation.

This design pattern is often referred to as "bare words", and I highly recommend the following RubyTapas episode on the subject: http://www.virtuouscode.com/2012/10/01/barewords/

I would also recommend that you have a quick read through a ruby style guide, to see what common conventions are considered "good" or "bad" by the community. (Ruby code styles are extremely well conformed to by the community!) For example, from this guide:

Only omit parentheses for

  • Method calls with no arguments:

    # bad
    Kernel.exit!()
    2.even?()
    fork()
    'test'.upcase()
    
    # good
    Kernel.exit!
    2.even?
    fork
    'test'.upcase
    

In your particular code above, although it's hard to say for sure without knowing more context, I suspect that subscription_checker should actually be abstracted into a separate class rather than yet-another-method in the controller. But as I say, in order to give any concrete advice here I'd need to see more of the source file this is taken from.

Upvotes: 4

Related Questions