How to define a method to be called from the configure block of a modular sinatra application?

Go To StackoverFlow.com

6

I have a Sinatra app that, boiled down, 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 doesn't work. I get undefined method read_config_file for MyApp:Class (NoMethodError)

The logic in read_config_file is non-trivial, so I don't want to duplicate in both. How can I define a method that can be called from both my configuration blocks? Or am I just approaching this problem in entirely the wrong way?

2012-04-05 02:25
by Seldo


5

It seems the configure block is executed as the file is read. You simply need to move 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
2012-04-05 02:55
by matt
Brilliant! That works. Now I have to go read a ruby book to find out what the hell the difference is between def methodname and def self.methodname, which is new syntax to me - Seldo 2012-04-05 17:35


0

Your configure blocks are run when the class definition is evaluated. So, the context is the class itself, not an instance. So, you need a class method, not an instance method.

def self.read_config_file

That should work. Haven't tested though. ;)

2012-04-05 02:36
by Sean McB
I'm afraid using self.read_config_file gives exactly the same error. Sorry, I should have specified that I'd already tried this :- - Seldo 2012-04-05 02:46
Damn it, I was so close. The second answerer is right. The class definition is interpreted as the file is read, and I guess those blocks are executed immediately by Sinatra, so you need to define the class method before you set up the configure lines - Sean McB 2012-04-05 03:10
Ads