commander-rb / commander

The complete solution for Ruby command-line executables
MIT License
822 stars 74 forks source link

state-changing behaviour inhibits `Commander::Command` reuse #67

Closed doriantaylor closed 6 years ago

doriantaylor commented 6 years ago

Greets,

I may be completely abusing this library but I figured out I could reuse the command parsing functionality in a shell loop. Only one problem: when Commander::Command#call is called, it empties the array where the code is kept. The net effect is that you can only #run it once.

I don't know enough about this package to know if it would mess anything else up to make these objects effectively immutable, but even something like this:

def call(args = [])
  object, meth = @when_called[0,2]
  meth ||= :call
  options = proxy_option_struct
  case object
  when Proc then object.call(args, options)
  when Class then meth != :call ? object.new.send(meth, args, options) : object.new(args, options)
  else object.send(meth, args, options) if object
  end
end

…would be non-destructive. Then there is the matter of @proxy_options being continually appended to via #option_proc, so it would have to be emptied after each #run, perhaps like this:

def proxy_option_struct!
  out = proxy_option_struct
  @proxy_options = []
  out
end

…and then just change that one line in #call. This is me just eyeballing it, so I have no idea if any of this would work/not break anything elsewhere. I can fork and PR this if there are no surprises.

Thanks,

doriantaylor commented 6 years ago

(okay so I was curious and hacked it in and it seems to pass existing tests, so, win?)

ggilder commented 6 years ago

Cool, please submit a PR and I'll take a look!

doriantaylor commented 6 years ago

coming up…