Class: Nitro::Compiler

Inherits:
Object
  • Object
show all
Defined in:
lib/nitro/compiler.rb

Overview

The Compiler transforms published methods (actions) and assorted template files (views) into specialized code that responds to a URI. The generated action methods are injects in the Controller that handles the URI.

Constant Summary collapse

PROTO_TEMPLATE_ROOT =
"#{Nitro.proto_path}/public"

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(controller = nil) ⇒ Compiler

Returns a new instance of Compiler.



81
82
83
84
# File 'lib/nitro/compiler.rb', line 81

def initialize(controller = nil)
  @controller = controller
  @shared = {}
end

Instance Attribute Details

#controllerObject

The controller for this compiler.



27
28
29
# File 'lib/nitro/compiler.rb', line 27

def controller
  @controller
end

#sharedObject

The compiler stages (compilers) can create multiple variables or accumulation bufffers to communicate with each other. Typically javascript and css acc-buffers are used. This is the shared memory used by the compilers.



34
35
36
# File 'lib/nitro/compiler.rb', line 34

def shared
  @shared
end

Class Method Details

.precompile(filename) ⇒ Object

Typically used to precompile css templates.



368
369
370
371
372
373
374
375
376
377
378
379
# File 'lib/nitro/compiler.rb', line 368

def precompile(filename)
  src = File.join(Template.root, "#{filename}t")
  dst = File.join(Server.public_root, filename)
  
  if (!File.exist?(dst)) or (File.mtime(src) > File.mtime(dst))
    Logger.info "Compiling template '#{src}' to '#{dst}'."
    template = FileTemplate.new(src)
    File.open(dst, 'w') do |f|
      f << template.process
    end
  end
end

Instance Method Details

#action?(sym) ⇒ Boolean

Helper.

Returns:

  • (Boolean)


116
117
118
# File 'lib/nitro/compiler.rb', line 116

def action?(sym)
  return @controller.action_methods.include?(sym.to_s)
end

#compile(action) ⇒ Object

Compiles an action method in the given (controller) class. A sync is used to make compilation thread safe.



359
360
361
# File 'lib/nitro/compiler.rb', line 359

def compile(action)
  compile_action(action)
end

#compile_action(action) ⇒ Object

Compiles an action. The generated action combines the action supplied by the programmer and an optional template in an optimized method to handle the input URI.

Passes the action name and the parent action name in the

Example

def my_method template_root/my_method.xhtml

are combined in:

def my_method_action

This generated method is called by the dispatcher.

Template root overloading

Nitro provides a nice method of template_root overloading that allows you to use OOP principles with templates. Lets say you have the following controller inheritance.

SpecificController < BaseController < Nitro::Controller

When the compiler tries to find a template for the SpecificController, it first looks into SC’s template root. If no suitable template is found, it looks into BaseController’s template_root etc. The final template_root is always the Nitro proto dir (the prototype application). This way you can reuse Controllers and templates and only overriding the templates as required by placing a template with the same name in the more specific template root. – TODO: cleanup this method. ++



215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# File 'lib/nitro/compiler.rb', line 215

def compile_action(action)    
  action = @action = action.to_s.gsub(/_action$/, '')

  return false unless action

  Logger.debug "Compiling action '#@controller##{action}'" if $DBG

  valid = false

  #--
  # FIXME: parent_action_name does not work as expected, 
  # if you include actions from other controllers!!
  #++
      
  code = %{
    def #{action}_action
      @parent_action_name = @action_name 
      @action_name = '#{action}'
  }

  # Inject the pre advices.

  code << ::Aspects.gen_advice_code(action, @controller.advices, :pre) 

  # Call the action
  
  if @controller.action_methods.include?(action)
    valid = true

    # Annotated parameters.

    if params = @controller.ann(action.to_sym).params and (!params.nil?)
      params = params.collect { |p| "@#{p} = @context['#{p}']" }
      code << "#{params.join(';')}"
    end
    
    arity = @controller.instance_method(action.to_sym).arity
    
    # Call action with given parameters, raises ActionError when the params
    # are wrong.
    # TODO: return 404 or other error code for browser?
    
    code << %{
      params = context.action_params || []
      
      # Fill not given parameters with nils
      
      arity = (#{arity} < -1) ? (#{arity}.abs - 1) : #{arity}
      if Nitro::Compiler.non_strict_action_calling
        arity.times {|i| params[i] ? nil : params[i] = nil }
      end
      
      # When arity zero, ignore params
      params.clear if arity == 0
      
      if Nitro::Compiler.mixin_get_parameters && params.empty? && arity > 0
        context.params.each_with_index do |(k,v),i|
          break if i > arity
          params << v
        end
      end
      
      begin
        action_return_value = #{action}(*params)
      rescue ArgumentError => e
        raise ActionError, "Wrong parameter count for \#{@action_name}(\#{params.join(', ')})."
      end
    }
    
    code << %{
      unless :stop == action_return_value      
    }
  end
  
  # Try to call the template method if it exists. It is a 
  # nice practice to put output related code in this method 
  # instead of the main action so that this method can be 
  # overloaded separately.
  #
  # If no template method exists, try to convert an external
  # template file into a template method. It is an even 
  # better practice to place the output related code in an 
  # external template file.

  # Take :template annotation into account.
  
  unless template = @controller.ann(action.to_sym)[:template] # FIXME
    template = action
  end

  # Search the [controller] class and it's ancestors for the template
  
  template_path = template_for_action(template.to_s) 
  if template_path or @controller.instance_methods.include?("#{action}_template")
    valid = true
    code << %{
      #{action}_template
    }
  end

  return false unless valid

  if @controller.action_methods.include?(action)
    code << %{
      if @out.empty? and action_return_value.is_a?(String)
        print(action_return_value)
      end
    end
    }
  end

  if Render.redirect_on_empty
    code << %{
      redirect_to_referer if @out.empty?
    }
  end

  # Inject the post advices.

  code << ::Aspects.gen_advice_code(action, @controller.advices, :post) 

  code << %{
      @action_name = @parent_action_name
    end
  }

  # First compile the action method. 
  
  @controller.class_eval(code)

  unless @controller.respond_to?("#{action}_template")
    # If there is not method {action}_template in the controller
    # search for a file template.
    if template_path 
      compile_template(action, template_path)
    end
  end

  return true
end

#compile_template(action, path) ⇒ Object

Compile the template into a render method. Don’t compile the template if the controller responds_to? #action_template.



163
164
165
166
167
168
169
170
171
172
173
174
175
# File 'lib/nitro/compiler.rb', line 163

def compile_template(action, path)
  Logger.debug "Compiling template '#{@controller}: #{path}'" if $DBG

  template = File.read(path)

  code = %{
    def #{action}_template
      #{transform_template(action, template)}
    end
  }
  
  @controller.class_eval(code, path)
end

#template_for_action(action, ext = Template.extension) ⇒ Object Also known as: template?

Traverse the template_root stack to find a template for this action.

Action names with double underscores (__) are converted to subdirectories. Here are some example mappings:

hello_world -> template_root/hello_world.xhtml this__is__my__hello_world -> template_root/this/is/my/hello_world



95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/nitro/compiler.rb', line 95

def template_for_action(action, ext = Template.extension)
  action = action.to_s
  for template_root in @controller.instance_variable_get(:@template_root)
    # attempt to find a template of the form
    # template_root/action.xhtml

    path = "#{template_root}/#{action.gsub(/__/, '/')}.#{ext}".squeeze('/')
    return path if File.exist?(path)
  
    # attempt to find a template of the form
    # template_root/action/index.xhtml

    path = "#{template_root}/#{action.gsub(/__/, '/')}/#{Template.default}.#{ext}".squeeze('/')
    return path if File.exist?(path) 
  end
  return nil      
end

#transform_template(action, template) ⇒ Object

This method transforms the template. Typically template processors are added as aspects to this method to allow for customized template transformation prior to compilation.

The default transformation extracts the Ruby code from processing instructions, and uses the StaticInclude, Morphing, Elements and Markup compiler modules.

The Template transformation stage is added by default.

You can override this method or use aspects for really special transformation pipelines. Your imagination is the limit. – TODO: make Template stage pluggable. gmosx: This method is also called from the scaffolding code. ++



140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/nitro/compiler.rb', line 140

def transform_template(action, template)
  # Check for an action specific transformation pipeline.
  if (transformers = @controller.ann(action.to_sym).transformation_pipeline).nil?
    # Check for a controller specific transformation pipeline.
    if (transformers = @controller.ann.self.transformation_pipeline).nil?
      # Use the default transformation pipeline.
      transformers = Compiler.transformation_pipeline
    end
  end

  transformers.each do |transformer|
    template = transformer.transform(template, self)
  end
  
  # Add Template transformation stage by default.
  
  template = Template.transform(template)
end