Search code examples
thor

Thor - how to use lambda functions for expressing default values on method_options


Suppose a method_option of the form:

method_option :host_domain,       aliases: '-h', default: 'some value'

Can a non-trivial lambda function be used in place of 'some value' to derive the default value at run time.

Something trivial like:

method_option :host_domain,       aliases: '-h', default: -> { 'some value'.upcase}.call

works fine.

However, something like:

method_option :host_domain,       aliases: '-h', default: -> { Model.method}.call

does not because it cannot find the Model instance (which is defined in app/lib/models & has already been loaded prior). It also seems at the point of the module_option statement, the Thor class has not been initialized. I guess thereby hangs a tale.hir

Further, in method def new, which follows the method_option statements, I can reference Model with out issue. I also note that the Thor class has been initialized prior to entry of the new method (as you would expect).

Would appreciate any guidance on how to navigate the Thor hierarchy to sort out the problem.


Solution

  • On further exploration, I found that delaying the execution of the lambda function solved the problem.

    That is, in the method new, call the lambda function as follows:

    Change:

    method_option :host_domain,       type: :string, default: -> {Model.method}.call
    

    to:

    method_option :host_domain,       type: :string, default: -> {Model.method}
    

    and in:

    def new(url)
      ...
      ...
      options[:host_domain] = options[:host_domain].call