0

I am currently building a Thor executable that supports several different tasks. Some tasks inoke other tasks. For example

  • Auth
    • authenticates the local user
  • Create
    • Invoke Auth
    • Does something
    • Invoke Configure
  • Configure:
    • Invoke Auth
    • Does something

The nice thing about thor is that I can now call all of the three tasks separately, but be sure that authenticate for example is only called once through invoke.

But what is now the best way to share Data between those tasks. For example when Authenticating I want to set the User-ID of the current user. Thus when I want to request Data from our webservice I can take the user id from anywhere in my code the same way.

Right now I am implementing this through Modules, but I am not really sure if this is the best way to do it.

Using Singleton would be another way, but somehow this seems like a little bit too much for this purpose.

Maybe you guys have experience with a better way to do this, or maybe using modules is the best way to store the information anyway.

Florian Motlik
  • 386
  • 3
  • 7

2 Answers2

1

I would have done something like this:

module PRJ

  class << self
    attr_accessor :api_key, :account_name, :api_version, :api_url, ......

    def configure
     yield self
    end
  end

end

require "#{directory_of_all_other_classes}"

require 'thor'

class CLI < Thor
include Thor::Actions

def login
  ...
  PRJ.api_key = response[:api_key] 
end

As you want to invoke Auth in every cases, so I think it should be in main CLI file.

Regarding storing and using data it would be better to use attributes instead of constant. I may not be right about this but I prefer using class attributes.

Now you can access and change PRJ.api_key from anywhere (require PRJ module in every file)

P.S. The structure of code snippet might not be accurate, I just wanted to share some basic skeleton. Do something like above for remaining classes.

Manish Das
  • 3,785
  • 2
  • 21
  • 34
0

If you just need to store simple data structures I would go for common class variables

class Test < Thor
  @@my_shared_var = nil 

  desc 'my_first_task','sdfasdf'
  def my_first_task
    @@my_shared_var = 'foo'
  end

  desc 'my_second_task','sdfasdf'
  def my_second_task
    invoke :my_first_task
    puts @@my_shared_var
  end

end
masciugo
  • 1,113
  • 11
  • 19