forked from bernd/fpm-cookery
/
book.rb
51 lines (41 loc) · 1.42 KB
/
book.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
require 'singleton'
require 'fpm/cookery/path'
module FPM
module Cookery
class Book
include Singleton
attr_accessor :filename, :config
def initialize
@recipe = nil
end
# Load the given file and instantiate an object. Wrap the class in an
# anonymous module to avoid namespace cluttering. (see Kernel.load)
def load_recipe(filename, config, &callback)
@filename = FPM::Cookery::Path.new(filename).realpath
@config = config
Kernel.load(@filename.to_path, true)
callback.call(@recipe.new)
end
def add_recipe_class(klass)
@recipe = klass
end
# Hijack the recipe singleton to make the +filename+ and +config+ objects
# available when a descendent of BaseRecipe is declared. This makes it
# possible to do Hiera lookups at class definition time.
def inject_class_methods!(klass)
# It's necessary to close over local variables because the receiver
# changes within the scope of +define_method+, so +self.filename+ would
# wrongly refer to +singleton_klass.filename+.
filename = self.filename
config = self.config
singleton_klass = (class << klass ; self ; end)
singleton_klass.send(:define_method, :filename) do
filename
end
singleton_klass.send(:define_method, :config) do
config
end
end
end
end
end