Should I define a main method in my ruby scripts?

纵然是瞬间 提交于 2019-11-29 20:16:14

I usually use

if __FILE__ == $0
  x = SweetClass.new(ARGV)
  x.run # or go, or whatever
end

So yes, you can. It just depends on what you are doing.

I've always found $PROGRAM_NAME more readable than using $0. Half the time that I see the "Perl-like" globals like that, I have to go look them up.


if __FILE__ == $PROGRAM_NAME
  # Put "main" code here
end

You should put library code in lib/ and executables, which require library code, in bin/. This has the additional advantage of being compatible with RubyGems's packaging method.

A common pattern is lib/application.rb (or preferably a name that is more appropriate for your domain) and bin/application, which contains:

require 'application'
Application.run(ARGV)

My personal rule of thumb is: the moment

if __FILE__ == $0
    <some code>
end

gets longer than 5 lines, I extract it to main function. This holds true for both Python and Ruby code. Without that code just looks poorly structured.

No.

Why add an extra layer of complexity for no real benefit? There's no convention for Rubyists that uses it.

I would wait until the second time you need to use it (which will probably happen less often than you think) and then refactor it so that it's reusable, which will probably involve a construct like the above.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!