Module: Spider::ControllerMixins::Visual

Defined in:
lib/spiderfw/controller/mixins/visual.rb

Overview

Mixin for objects using templates

Defined Under Namespace

Modules: ClassMethods, OutputFormatMethods

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#dispatcher_layoutObject

Returns the value of attribute dispatcher_layout.



9
10
11
# File 'lib/spiderfw/controller/mixins/visual.rb', line 9

def dispatcher_layout
  @dispatcher_layout
end

#layoutObject

Returns the value of attribute layout.



9
10
11
# File 'lib/spiderfw/controller/mixins/visual.rb', line 9

def layout
  @layout
end

#templateObject (readonly)

Returns the value of attribute template.



8
9
10
# File 'lib/spiderfw/controller/mixins/visual.rb', line 8

def template
  @template
end

Class Method Details

.define_format_annotations(klass) ⇒ Object



17
18
19
20
21
22
# File 'lib/spiderfw/controller/mixins/visual.rb', line 17

def self.define_format_annotations(klass)
    klass.define_annotation(:html) { |k, m, params| k.output_format(m, :html, params) }
    klass.define_annotation(:xml) { |k, m, params| k.output_format(m, :xml, params) }
    klass.define_annotation(:json) { |k, m, params| k.output_format(m, :json, params) }
    klass.define_annotation(:text) { |k, m, params| k.output_format(m, :text, params) }
end

.included(klass) ⇒ Object



11
12
13
14
15
# File 'lib/spiderfw/controller/mixins/visual.rb', line 11

def self.included(klass)
   klass.extend(ClassMethods)
   klass.extend(OutputFormatMethods)
   define_format_annotations(klass)
end

Instance Method Details

#after_widget(id) ⇒ Object

Callback executed after child widgets are run. Useful to postprocess widgets data. id is the child widget id, as a symbol.



263
264
# File 'lib/spiderfw/controller/mixins/visual.rb', line 263

def after_widget(id)
end

#before(action = '', *params) ⇒ Object



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
52
53
54
55
56
57
58
59
60
61
# File 'lib/spiderfw/controller/mixins/visual.rb', line 24

def before(action='', *params)
    unless self.respond_to?(:serving_static?) && self.serving_static?
        @layout ||= self.class.get_layout(action)
        @layout ||= @dispatcher_layout
        n_route = dispatch_next(action)
        obj = n_route.obj if n_route
        if obj.is_a?(Visual) && !(obj.respond_to?(:serving_static?) && obj.serving_static?)
            set_layout = @layout
            if set_layout
                set_layout = [set_layout] unless set_layout.is_a?(Array)
                set_layout.map{ |l| self.class.load_layout(l) }
                obj.dispatcher_layout = set_layout
            end
        end
    end
    return super unless action_target?
    format = nil
    req_format = self.is_a?(Widget) && @is_target && @request.params['_wf'] ? @request.params['_wf'].to_sym : @request.format
    if (req_format && self.class.output_formats[@executed_method])
        format = req_format if self.class.output_format?(@executed_method, req_format)
        if (format)
            format_params = self.class.output_format_params(@executed_method, format)
        end
        if @executed_method && !format || (format_params && format_params[:widgets] && !target_mode?)
            #raise Spider::Controller::NotFound.new("#{action}.#{@request.format}") 
        end
    end
    format ||= self.class.output_format(@executed_method)
    format_params ||= self.class.output_format_params(@executed_method, format)
    output_format_headers(format)
    @executed_format = format
    @executed_format_params = format_params
    if Spider.runmode != 'devel' && File.exists?(File.join(Spider.paths[:tmp], 'maintenance.txt'))
        raise Spider::Controller::Maintenance
    end
   
    super
end

#build_backtrace(exc) ⇒ Object



357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
# File 'lib/spiderfw/controller/mixins/visual.rb', line 357

def build_backtrace(exc)
    bt = []
    if Object.const_defined?(:Debugger) && Debugger.started? && Debugger.post_mortem?
        use_debugger = true
        context = exc.__debug_context
        ct_first_file = context.frame_file(0)
        ct_first_line = context.frame_line(0)
        e_file, e_line, e_method = exc.backtrace[0].split(':')
        if (e_file != ct_first_file || e_line.to_i != ct_first_line)
            use_debugger = false
        end
    end
    if (!use_debugger)
        exc.backtrace.each do |trace_line|
            str = trace_line
            file_path, line, method = trace_line.split(':')
            bt << {:text => str, :path => file_path, :line => line, :method => method}
        end
        return bt
    end
    context = exc.__debug_context
    seen_obj = {}
    0.upto(Debugger.current_context.stack_size - 2) do |i|
        begin
            file = context.frame_file(i)
            line = context.frame_line(i)
            klass = context.frame_class(i)
            method = context.frame_method(i)
            #break if File.basename(file) == 'controller.rb' && locals.key?("spider_main_controller_send")
            unless Spider.conf.get('devel.trace.show_framework')
                next if file.index($SPIDER_PATH) == 0
            end
            args = context.frame_args(i)
            locals = context.frame_locals(i)
            frame_self = context.frame_self(i)
            dest = context.frame_self(i-1) unless i == 0
            ex_method = context.frame_method(i-1) unless i == 0
            in_method = context.frame_method(i)
    #s                ex_args = context.frame_args(i+1)
            str = "#{file}:#{line}: in #{in_method}"
            #str = exc.backtrace[i]
        
            self_str = frame_self
    #                self_str = "#<#{frame_self.class}:#{frame_self.object_id}>"
            if (dest)
                dest_str = dest.is_a?(Class) ? dest.inspect : "#<#{dest.class}:#{dest.object_id}>"
            else
                dest_str = ""
            end
            self_str = frame_self.is_a?(Class) ? frame_self.inspect : "#<#{frame_self.class}:#{frame_self.object_id}>"

            # if (frame_self == dest)
            #                        info = "#{dest_str}"
            #                    else
            #                        info = "#{self_str}: #{dest_str}"
            #                    end
            info = "#{self_str}: #{dest_str}"
            info += ".#{ex_method}("
            info += args.map{ |arg|
                val = locals[arg]
                arg_str = "#{arg}##{val.class}"
                val_str = nil
                if (val.is_a?(String))
                    if (val.length > 20)
                        val_str = (val[0..20]+'...').inspect
                    else
                        val_str = val.inspect
                    end
                elsif (val.is_a?(Symbol) || val.is_a?(Fixnum) || val.is_a?(Float) || val.is_a?(BigDecimal) || val.is_a?(Date) || val.is_a?(Time))
                    val_str = val.inspect
                end
                arg_str += "=#{val_str}" if val_str
                arg_str
            }.join(', ')
            info += ")"

            iv = nil
            if !seen_obj[frame_self.object_id] && Spider.conf.get('devel.trace.show_instance_variables')
                iv = {}
                frame_self.instance_variables.each{ |var| iv[var] = frame_self.instance_variable_get(var) }
                iv.reject{ |k, v| v.nil? }
            end
            locals = nil unless Spider.conf.get('devel.trace.show_locals')
            bt << {
                :text => str, :info => info, 
                :path => File.expand_path(file), :line => line, :method => method, :klass => klass, :locals => locals,
                :self => frame_self.object_id,
                :instance_variables => iv,
                :first_seen => !seen_obj[frame_self.object_id]
            }
            seen_obj[frame_self.object_id] = true
        rescue => exc2
        end
    end
    return bt
end

#execute(action = '', *params) ⇒ Object



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/spiderfw/controller/mixins/visual.rb', line 98

def execute(action='', *params)
    @visual_params = @executed_format_params
    @is_target = false if target_mode? && !self.is_a?(Spider::Widget)
    if (self.is_a?(Widget) && @is_target && @request.params['_wp'])
        params = @request.params['_wp']
    elsif (@visual_params.is_a?(Hash) && @visual_params[:params])
        p_first, p_rest = action.split('/')
        params = format_params[:params].call(p_rest) if p_rest
    end
    super(action, *params)
    return unless @visual_params.is_a?(Hash)
    @template = get_template if !@template && @visual_params[:template]
    init_widgets(@template) if @template
    if @visual_params[:call]
        meth = self.method(@visual_params[:call])
        args = params + @executed_method_arguments
        arity = meth.arity
        arity = (-arity + 1) if arity < 0
        args = arity == 0 ? [] : args[0..(arity-1)]
        args = [nil] if meth.arity == 1 && args.empty?
        send(@visual_params[:call], *args)
    end
    if @visual_params[:template] && !@_widget && !done?
        if (@template)
            render(@template, @visual_params)  # has been init'ed in before method
        else
            render(@visual_params[:template], @visual_params)
        end
    end
    if @visual_params[:redirect]
        redirect(@visual_params[:redirect])
    end
    if @executed_format == :json && (@visual_params[:scene] || @visual_params[:return]) # FIXME: move in JSON mixin?
        if (@visual_params[:return])
            $out << @visual_params[:return].to_json
        elsif (@visual_params[:scene].is_a?(Array))
            h = @scene.to_hash
            res = {}
            @visual_params[:scene].each{ |k| res[k] = h[k] }
            $out << res.to_json
        else
            $out << @scene.to_json
        end
    end
end

#find_widget(name) ⇒ Object



257
258
259
# File 'lib/spiderfw/controller/mixins/visual.rb', line 257

def find_widget(name)
    @template.find_widget(name)
end

#get_template(path = nil, scene = nil, options = {}) ⇒ Object



169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# File 'lib/spiderfw/controller/mixins/visual.rb', line 169

def get_template(path=nil, scene=nil, options={})
    return @template if @template && @loaded_template_path == path
    scene ||= @scene
    scene ||= get_scene
    if (!path)
        format_params = @visual_params || self.class.output_format_params(@executed_method, @executed_format)
        return unless format_params && format_params[:template]
        path = format_params[:template]
        options = format_params.merge(options)
    end
    template = load_template(path)
    init_template(template, options)            
    @template = template
    @loaded_template_path = path

    return template
end

#init_layout(layout) ⇒ Object



200
201
202
203
204
# File 'lib/spiderfw/controller/mixins/visual.rb', line 200

def init_layout(layout)
    l = layout.is_a?(Layout) ? layout : self.class.load_layout(layout)
    prepare_template(l)
    return l
end

#init_template(template = nil, options = {}) ⇒ Object



187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/spiderfw/controller/mixins/visual.rb', line 187

def init_template(template=nil, options={})
    return get_template(template, nil, options) unless template.is_a?(Spider::Template)
    prepare_template(template) unless template.owner # if called directly
    template.init(scene)
    if (@request.params['_action'])
        template._widget_action = @request.params['_action']
    else
        template._action_to = options[:action_to]
        template._action = @controller_action
    end
    return template
end

#init_widgets(template, layout = nil) ⇒ Object



76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# File 'lib/spiderfw/controller/mixins/visual.rb', line 76

def init_widgets(template, layout=nil)
    widget_target = @request.params['_wt']
    widget_execute = @request.params['_we']
    if (widget_target && !@rendering_error)
        first, rest = widget_target.split('/', 2)
        @_widget = template.find_widget(first)
        @_widget = layout.find_widget(first) if !@_widget && layout
        raise Spider::Controller::NotFound.new("Widget #{widget_target}") unless @_widget
        @_widget.is_target = true unless rest
        @_widget.set_action(widget_execute) if widget_execute
        @_widget.is_target_ancestor = true
        @_widget.widget_target = rest
    end
    template.do_widgets_before
    layout.do_widgets_before if layout
    if @_widget
        @_widget.before(widget_execute) if @_widget.is_target
        @_widget.execute
        done
    end
end

#load_template(path, cur_path = nil, owner = nil, search_paths = nil) ⇒ Object



144
145
146
147
148
149
# File 'lib/spiderfw/controller/mixins/visual.rb', line 144

def load_template(path, cur_path=nil, owner=nil, search_paths=nil)
    template = self.class.load_template(path, cur_path, owner, search_paths)
    prepare_template(template)
    @template = template
    return template
end

#load_template_from_path(path, definer) ⇒ Object



151
152
153
154
155
156
# File 'lib/spiderfw/controller/mixins/visual.rb', line 151

def load_template_from_path(path, definer)
    t = Spider::Template.new(path)
    t.owner_class = self.class
    t.definer_class = definer
    t
end

#output_format_headers(format) ⇒ Object



63
64
65
66
# File 'lib/spiderfw/controller/mixins/visual.rb', line 63

def output_format_headers(format)
    return content_type('application/json') if format == :json && Spider.runmode == 'devel' && @request.params['_text']
    content_type(format)
end

#prepare_template(template) ⇒ Object



158
159
160
161
162
# File 'lib/spiderfw/controller/mixins/visual.rb', line 158

def prepare_template(template)
    template.owner = self
    template.request = request
    template.response = response
end

#render(path = nil, options = {}) ⇒ Object



206
207
208
209
210
211
212
213
214
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
# File 'lib/spiderfw/controller/mixins/visual.rb', line 206

def render(path=nil, options={})
    scene = options[:scene] || @scene
    scene ||= get_scene
    scene = prepare_scene(scene) unless options[:no_prepare_scene]
    request = options[:request] || @request
    response = options[:response] || @response
    if (path.is_a?(Spider::Template))
        template = path
    else
        template = get_template(path, scene, options)
    end
    layout = nil
    unless options.key?(:layout) && !options[:layout]
        chosen_layouts = options[:layout] || @layout
        chosen_layouts = [chosen_layouts] if chosen_layouts && !chosen_layouts.is_a?(Array)
        if (chosen_layouts)
            t = template
            layout = nil
            (chosen_layouts.length-1).downto(0) do |i|
                layout = init_layout(chosen_layouts[i])
                layout.template = t
                t = layout
            end
        end
        layout.init(scene) if layout
    end
    init_widgets(template, layout)
    return template if done?

    if layout
        layout.render(scene)
    else
        template.render(scene)
    end
    return template
end

#render_error(path, options) ⇒ Object



252
253
254
255
# File 'lib/spiderfw/controller/mixins/visual.rb', line 252

def render_error(path, options)
    options[:no_prepare_scene] = true
    render(path, options)
end

#render_to_string(*args) ⇒ Object



243
244
245
246
247
248
249
250
# File 'lib/spiderfw/controller/mixins/visual.rb', line 243

def render_to_string(*args)
    res = StringIO.new
    $out.output_to(res) do
        render(*args)
    end
    res.rewind
    res.read
end

#send_error_email(exc) ⇒ Object



340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
# File 'lib/spiderfw/controller/mixins/visual.rb', line 340

def send_error_email(exc)
    scene = Spider::Scene.new
    scene.request = @request.env
    scene.exception = exc
    subject = _("Site error")
    if Spider.conf.get('orgs.default.name')
        subject = "#{Spider.conf.get('orgs.default.name')} - #{subject}"
    elsif @request.env.key?('HTTP_HOST')
        subject = "#{@request.env['HTTP_HOST']} - #{subject}" 
    end
    headers = {'Subject' => subject}
    from = Spider.conf.get('orgs.default.auto_from_email') || Spider.conf.get('site.tech_admin.email')
    Spider::Messenger::MessengerHelper.send_email(
        self.class, 'error', scene, from, Spider.conf.get('site.tech_admin.email'), headers
    )
end

#target_mode?Boolean

Returns:

  • (Boolean)


72
73
74
# File 'lib/spiderfw/controller/mixins/visual.rb', line 72

def target_mode?
    !@request.params['_wt'].nil? && !@request.params['_wt'].empty?
end

#template_exists?(name) ⇒ Boolean

Returns:

  • (Boolean)


164
165
166
# File 'lib/spiderfw/controller/mixins/visual.rb', line 164

def template_exists?(name)
    self.class.template_exists?(name)
end

#try_rescue(exc) ⇒ Object



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
# File 'lib/spiderfw/controller/mixins/visual.rb', line 269

def try_rescue(exc)
    if exc.respond_to?(:uuid=)
        return super if exc.uuid # Error page already outputted
        exc.uuid = SecureRandom.hex(12)
    end
    format = self.class.output_format(:error) || :html
    unless exc.is_a?(Spider::Controller::Maintenance) || exc.is_a?(Spider::Controller::NotFound)
        return super unless @executed_format == :html
        return super unless action_target?
        return super if target_mode?
    end
    output_format_headers(format)
    layout = 'errors/error'
    if exc.is_a?(Spider::Controller::Maintenance)
        error_page = 'maintenance'
        layout = 'generic'
    elsif exc.is_a?(Spider::Controller::NotFound)
        error_page = 'errors/404'
        layout = 'errors/simple'
        @scene.error_msg = _("Page not found")
        @scene.email_subject = @scene.error_msg
    else
        error_page = 'errors/error_generic'
        if (exc.is_a?(HTTPMixin::HTTPStatus))
            @scene.error_msg = exc.status_message
        end
        @scene.error_msg = _("An error occurred")
        @scene.email_subject = @scene.error_msg
    end
    
    if exc.respond_to?(:uuid)
        exc.extend(UUIDExceptionMessage)
        @scene.exception_uuid = exc.uuid
        @scene.email_subject += " (#{exc.uuid})" if @scene.email_subject
    end
    @scene.admin_email = Spider.conf.get('site.tech_admin.email')
    if Spider.runmode == 'devel'
        begin
            @scene.devel = true
            @scene.backtrace = build_backtrace(exc)
            client_editor = Spider.conf.get('client.text_editor')
            prefix = 'txmt://open?url=' if client_editor == 'textmate'
            @scene.exception = "#{exc.class.name}: #{CGI.escapeHTML(exc.message)}"
            cnt = 0
            @scene.backtrace.each do |tr|
                tr[:index] = cnt
                cnt += 1
                suffix = ''
                suffix = "&line=#{tr[:line]}" if (client_editor == 'textmate')
                tr[:link] = "#{prefix}file://#{tr[:path]}#{suffix}"
            end
            @scene.request_params = @request.params.inspect
            @scene.session = @request.session.inspect
        rescue => exc2
            super(exc)
        end
    end
    @rendering_error = true
    @scene.__is_error_page = true
    unless exc.is_a?(Spider::Controller::NotFound)
        if Spider.const_defined?(:Messenger) && Spider.conf.get('errors.send_email') && Spider.conf.get('site.tech_admin.email')
            begin
                send_error_email(exc)
            rescue => exc2
            end
        end
    end
    render_error "#{error_page}", :layout => layout
    super
end

#visual_paramsObject



68
69
70
# File 'lib/spiderfw/controller/mixins/visual.rb', line 68

def visual_params
    @visual_params ||= {}
end