How to define a method to call from a configure block of a sinatra modular application?

I have a Sinatra application that, when cooked, looks basically like this:

class MyApp < Sinatra::Base configure :production do myConfigVar = read_config_file() end configure :development do myConfigVar = read_config_file() end def read_config_file() # interpret a config file end end 

Unfortunately this does not work. I get an undefined method read_config_file for MyApp:Class (NoMethodError)

The logic in read_config_file non-trivial, so I don't want to duplicate it in both. How can I determine a method that can be called from both of my configuration blocks? Or am I just completely approaching this problem?

+6
source share
2 answers

It seems that the configure block executes when reading the file. You just need to transfer the definition of your method before the configure block and convert it to a class method:

 class MyApp < Sinatra::Base def self.read_config_file() # interpret a config file end configure :production do myConfigVar = self.read_config_file() end configure :development do myConfigVar = self.read_config_file() end end 
+5
source

Your configuration blocks are triggered by class evaluation. So context is the class itself, not the instance. So, you need a class method, not an instance method.

 def self.read_config_file 

That should work. Not tested .;)

0
source

Source: https://habr.com/ru/post/912451/


All Articles