Parse and Run OptionParser with options directly from Crystal

Following is the describe for my need.

i create a new cli app, assume, named, myip, it invoke some web service, but that service broken (500) frequently.

when the 500 responsed, i want to invoke myip with myip -l to use another service, so, i am curious if there are any way to run myip -l directly within Crystal Code use OptionParser.

Thank you.

1 Like

It would probably be easier/better to just call the same code that myip -l would run versus creating a subprocess to call the actual binary again. I.e. your error handling logic calls a shard method that would be the same as option parser would do when passed the -l option.

As you would see here, all code(methods) which request web service pass same channel as parameter for async, they share some common select/when logic, those cause many duplicate code if just call the same code

For now, i have to create a subprocess to call the actual binary again to satisfied my need.

if ip111_500 == true
    system("#{Process.executable_path} -l")
end

I think it would be would be worthwhile structuring your code so that the main entrypoint file that uses OptionParser only handles parsing the input and then calls into the core logic required from another file. This way the core logic isn’t tightly coupled to the CLI context. E.g. oq/src/oq_cli.cr at master · Blacksmoke16/oq · GitHub. This would make it easier to share logic such that you do not have to create a subprocess like that.

Also why do you have all your logic define within an at_exit handler? That seems a bit strange…

Okay, i refactor my code follow your advice, it work well, thank you.

Also why do you have all your logic define within an at_exit handler? That seems a bit strange…

I copy it from somewhere, probably here?

@sdogruyol , could you please explain why?