Class: Catlass::DSLContext

Inherits:
Object
  • Object
show all
Defined in:
lib/catlass/dsl_context.rb

Instance Method Summary collapse

Constructor Details

#initializeDSLContext

Returns a new instance of DSLContext.



5
6
7
8
9
# File 'lib/catlass/dsl_context.rb', line 5

def initialize
  @jobs = []
  @templates = {}
  @context = Hashie::Mash.new()
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, &block) ⇒ Object



17
18
19
20
21
22
23
24
25
# File 'lib/catlass/dsl_context.rb', line 17

def method_missing(method_name, *args, &block)
  if [:Job].include?(method_name)
    hash = dslh_eval(block)
    hash['attributes']['name'] = args[0]
    @jobs << hash
  else
    super
  end
end

Instance Method Details

#contextObject



31
32
33
# File 'lib/catlass/dsl_context.rb', line 31

def context
  @context
end

#dslh_eval(block) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/catlass/dsl_context.rb', line 47

def dslh_eval(block)
  scope_hook = proc do |scope|
    scope.instance_eval(<<-'EOS')
      def include_template(template_name, context = {})
        tmplt = @templates[template_name.to_s]

        unless tmplt
          raise "Template '#{template_name}' is not defined"
        end

        context_orig = @context
        @context = @context.merge(context)
        instance_eval(&tmplt)
        @context = context_orig
      end

      def context
        @context
      end

      def __dsl(&block)
        @__hash__ = JSON.generate(Dslh::ScopeBlock.nest(binding, 'block'))
      end

      def __script(str)
        str.split(/\R/)
      end

      def __script_file(file)
        File.read(file).split(/\R/)
      end
    EOS
  end

  scope_vars = {templates: @templates, context: @context}

  Dslh.eval(allow_empty_args: true, scope_hook: scope_hook, scope_vars: scope_vars, &block)
end

#eval_dsl(dsl_file) ⇒ Object



11
12
13
14
15
# File 'lib/catlass/dsl_context.rb', line 11

def eval_dsl(dsl_file)
  @_dsl_file = dsl_file
  instance_eval(File.read(dsl_file), dsl_file)
  @jobs
end

#require(file) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
# File 'lib/catlass/dsl_context.rb', line 35

def require(file)
  jobfile = (file =~ %r|\A/|) ? file : File.expand_path(File.join(File.dirname(@_dsl_file), file))

  if File.exist?(jobfile)
    instance_eval(File.read(jobfile), jobfile)
  elsif File.exist?(jobfile + '.rb')
    instance_eval(File.read(jobfile + '.rb'), jobfile + '.rb')
  else
    Kernel.require(file)
  end
end

#template(name, &block) ⇒ Object



27
28
29
# File 'lib/catlass/dsl_context.rb', line 27

def template(name, &block)
  @templates[name.to_s] = block
end