Module: RbbtHTMLHelpers

Included in:
Entity::REST, Sinatra::SinatraRbbt
Defined in:
lib/rbbt/workflow/rest/render.rb,
lib/rbbt/workflow/rest/helpers.rb

Defined Under Namespace

Classes: TemplateNotFoundError

Constant Summary collapse

PAGESIZE =
25

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Class Attribute Details

.default_workflow_viewsObject

Returns the value of attribute default_workflow_views.



7
8
9
# File 'lib/rbbt/workflow/rest/render.rb', line 7

def default_workflow_views
  @default_workflow_views
end

Class Method Details

.locate_file(workflow, task, file, entity = nil) ⇒ Object



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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/rbbt/workflow/rest/render.rb', line 12

def self.locate_file(workflow, task, file, entity = nil)
  fixed_file = case
         when file =~  /\.[a-z]{2,4}$/
           file
         when file =~ /(.*)\/$/
           $1
         else
           file + '.haml'
         end

  if File.exists? file
    path = Path.setup(File.join('.', file))
    Log.debug "File #{[workflow, task, file, entity].collect{|v| "'#{ v }'"} * ", "} located at #{ path }"
    return path
  end

  path = nil
  [file, fixed_file].uniq.each do |f|

    webapp_views = Rbbt.www.views.find(:lib, Sinatra::Application.root)
    global_views = Rbbt.share.views

    workflow_views = case
                     when (not workflow.nil? and workflow.respond_to? :libdir and not Path === workflow.libdir)
                       workflow.libdir.www.views
                     when Path === default_workflow_views
                       default_workflow_views
                     else
                       nil
                     end

    entity_views = case
                   when Path === entity
                     entity
                   when Resource === entity
                     entity.www.views
                   when (Workflow === entity and not entity.libdir.nil?)
                     entity.libdir.www.views
                   else
                     nil
                   end
      
    [webapp_views, entity_views, workflow_views, global_views].compact.each do |resource_path|

      path = case
             when resource_path[workflow][task][f].exists?
               resource_path[workflow][task][f]
             when resource_path[task][f].exists?
               resource_path[task][f]
             when resource_path[workflow][f].exists?
               resource_path[workflow][f]
             when resource_path[f].exists?
               resource_path[f]
             end

      break unless path.nil?
    end
    break unless path.nil?
  end

  raise TemplateNotFoundError, "File not found: #{[workflow, task, file, entity].compact * ", "}" if path.nil?
  Log.debug "File #{[workflow, task, file, entity].collect{|v| "'#{ v }'"} * ", "} located at #{ path }"
  path
end

Instance Method Details

#add_user_defaults(user, entity, action, params) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/rbbt/workflow/rest/helpers.rb', line 50

def add_user_defaults(user, entity, action, params)
  return params if params.delete :no_defaults
  key = [user, entity, action] * ":"

  user_action_defaults.read_and_close do
    if user_action_defaults.include?(key) and not user_action_defaults[key] == :clear and not user_action_defaults[key].nil?
      Log.debug("Loading user defaults for #{key}")
      new = (user_action_defaults[key] || {} ).dup.merge(params)
      new.each do |key, value|
        next if params.include? key
        params[key] = value
      end
    end
  end

  params
end

#clean_list_id(list_id) ⇒ Object



5
6
7
# File 'lib/rbbt/workflow/rest/helpers.rb', line 5

def clean_list_id(list_id)
  list_id.gsub('/', '_')
end

#clear_user_defaults(user, entity, action) ⇒ Object



94
95
96
97
98
99
100
# File 'lib/rbbt/workflow/rest/helpers.rb', line 94

def clear_user_defaults(user, entity, action)
  key = [user, entity, action] * ":"
  Log.debug("Clearing user defaults for #{key}")
  user_action_defaults.write_and_close do
    user_action_defaults[key] = :clear
  end
end

#entity_action_render(entity_type, action, locals, &block) ⇒ Object



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/rbbt/workflow/rest/render.rb', line 376

def entity_action_render(entity_type, action, locals, &block)
  entity_type, format = entity_type.split ":"

  locals[:entity_type] = entity_type
  locals[:action] = action


  size = locals.delete(:_size) || locals.delete("_size") || :normal
  entity = setup_entity(entity_type, format, locals[:entity], locals)

  entity_class = case
                 when Entity.formats.include?(format)
                   Entity.formats[format] 
                 when Entity.formats.include?(entity_type)
                   Entity.formats[entity_type] 
                 else
                   nil
                 end

  workflow = WorkflowREST.workflows.last

  path = nil
  begin
    entity_resources = [] 
    entity_resources << entity.action_template if entity.respond_to? :action_template
    entity_resources << entity if Resource === entity or Workflow === entity
    entity_resources << entity_class.action_template if entity_class.respond_to? :action_template
    entity_resources << entity_class if Resource === entity_class or Workflow === entity_class
    entity_resources << [nil]

    entity_resources.each do |entity_resource|
      [format, entity_type].compact.each do |name|

        begin
          case size.to_sym
          when :normal
            file = File.join('entity', name, action + '.haml')
            path = locate_file(workflow, nil, file, entity_resource)
          when :small
            file_small = File.join('entity', name, action + '.small.haml')
            path = locate_file(workflow, nil, file_small, entity_resource)
          end
        rescue TemplateNotFoundError
          next
        end

        break unless path.nil?
      end
      break unless path.nil?
    end
    raise TemplateNotFoundError if path.nil?
  rescue TemplateNotFoundError
    if size.to_sym == :small
      size = :normal
      retry
    end
  end

  raise "Action template not found for type, format: #{[entity_type, format] * ", "}: #{ action }" if path.nil?

  layout = locals[:_layout]
  layout = false if locals[:_xhr] and layout.nil?
  layout = true if layout.nil?

  renderer = Haml::Engine.new(path.read, :filename => path.find)

  case
  when (not layout)
    renderer.render(self, locals, &block)
  when (not block_given?)
    workflow_render("layout", nil, nil, locals) do 
      renderer.render(self, locals) 
    end
  else
    renderer.render(self, locals, &block)
  end
end

#entity_list_action_render(entity_type, action, locals, &block) ⇒ Object



534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
# File 'lib/rbbt/workflow/rest/render.rb', line 534

def entity_list_action_render(entity_type, action, locals, &block)
  entity_type, format = entity_type.split ":"

  locals[:entity_type] = entity_type
  locals[:action] = action

  size = locals.delete(:_size) || locals.delete("_size") || :normal

  list = locals[:list] = Entity::REST.load_list(entity_type, locals[:id], user)

  entity_class = case
                 when Entity.formats.include?(format)
                   Entity.formats[format] 
                 when Entity.formats.include?(entity_type)
                   Entity.formats[entity_type] 
                 else
                   nil
                 end

  workflow = WorkflowREST.workflows.last

  path = nil
  begin
    entity_resources = [] 
    entity_resources << list.list_action_template if list.respond_to? :list_action_template
    entity_resources << list if Resource === list or Workflow === list
    entity_resources << entity_class.list_action_template if entity_class.respond_to? :list_action_template
    entity_resources << entity_class if Resource === entity_class or Workflow === entity_class
    entity_resources << [nil]

    entity_resources.each do |entity_resource|
      [format, entity_type, "Default"].compact.each do |name|

        begin
          case size.to_sym
          when :normal
            file = File.join('entity_list', name, action + '.haml')
            path = locate_file(workflow, nil, file, entity_resource)
          when :small
            file_small = File.join('entity_list', name, action + '.small.haml')
            path = locate_file(workflow, nil, file_small, entity_resource)
          end
        rescue TemplateNotFoundError
          next
        end

        break unless path.nil?
      end
      break unless path.nil?
    end
    raise TemplateNotFoundError if path.nil?
  rescue TemplateNotFoundError
    if size.to_sym == :small
      size = :normal
      retry
    end
  end

  raise "List action template not found for type, format: #{[entity_type, format] * ", "}: #{ action }" if path.nil?


  layout = locals[:_layout]
  layout = false if locals[:_xhr] and layout.nil?
  layout = true if layout.nil?

  renderer = Haml::Engine.new(path.read, :filename => path.find)

  case
  when (not layout)
    renderer.render(self, locals, &block)
  when (not block_given?)
    workflow_render("layout", nil, nil, locals) do 
      renderer.render(self, locals) 
    end
  else
    renderer.render(self, locals, &block)
  end

end

#entity_list_render(entity_type, locals, &block) ⇒ Object



454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
# File 'lib/rbbt/workflow/rest/render.rb', line 454

def entity_list_render(entity_type, locals, &block)
  entity_type, format = entity_type.split ":"

  size = locals.delete(:_size) || locals.delete("_size") || :normal

  locals[:entity_type] = entity_type
  locals[:format] = format

  list = locals[:list] = Entity::REST.load_list(locals[:entity_type], locals[:id], user)

  entity_class = case
                 when Entity.formats.include?(format)
                   Entity.formats[format] 
                 when Entity.formats.include?(entity_type)
                   Entity.formats[entity_type] 
                 else
                   nil
                 end

  workflow = WorkflowREST.workflows.last

  path = nil
  begin
    entity_resources = [] 
    entity_resources << list.list_template if list.respond_to? :list_template
    entity_resources << list if Resource === list or Workflow === list
    entity_resources << entity_class.list_template if entity_class.respond_to? :list_template
    entity_resources << entity_class if Resource === entity_class or Workflow === entity_class
    entity_resources << [nil]

    entity_resources.each do |entity_resource|
      [format, entity_type, "Default"].compact.each do |name|

        begin
          case size.to_sym
          when :normal
            file = File.join('entity_list', name + '.haml')
            path = locate_file(workflow, nil, file, entity_resource)
          when :small
            file_small = File.join('entity_list', name + '.small.haml')
            path = locate_file(workflow, nil, file_small, entity_resource)
          end
        rescue TemplateNotFoundError
          next
        end

        break unless path.nil?
      end
      break unless path.nil?
    end
    raise TemplateNotFoundError if path.nil?
  rescue TemplateNotFoundError
    if size.to_sym == :small
      size = :normal
      retry
    end
  end

  raise "List template not found for type, format: #{[entity_type, format] * ", "}" if path.nil?

  layout = locals[:_layout]
  layout = false if locals[:_xhr] and layout.nil?
  layout = true if layout.nil?

  renderer = Haml::Engine.new(path.read, :filename => path.find)

  case
  when (not layout)
    renderer.render(self, locals, &block)
  when (not block_given?)
    workflow_render("layout", nil, nil, locals) do 
      renderer.render(self, locals) 
    end
  else
    renderer.render(self, locals, &block)
  end
end

#entity_render(entity_type, locals, &block) ⇒ Object



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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
# File 'lib/rbbt/workflow/rest/render.rb', line 301

def entity_render(entity_type, locals, &block)
  entity_type, format = entity_type.split ":"

  size = locals.delete(:_size) || locals.delete("_size") || :normal

  entity = setup_entity(entity_type, format, locals[:entity], locals)

  entity_class = case
                 when Entity.formats.include?(format)
                   Entity.formats[format] 
                 when Entity.formats.include?(entity_type)
                   Entity.formats[entity_type] 
                 else
                   nil
                 end

  workflow = WorkflowREST.workflows.last

  path = nil
  begin
    entity_resources = [] 
    entity_resources << entity.template if entity.respond_to? :template
    entity_resources << entity if Resource === entity or Workflow === entity
    entity_resources << entity_class.template if entity_class.respond_to? :template
    entity_resources << entity_class if Resource === entity_class or Workflow === entity_class
    entity_resources << [nil]

    entity_resources.each do |entity_resource|
      [format, entity_type].compact.each do |name|

        begin
          case size.to_sym
          when :normal
            file = File.join('entity', name + '.haml')
            path = locate_file(workflow, nil, file, entity_resource)
          when :small
            file_small = File.join('entity', name + '.small.haml')
            path = locate_file(workflow, nil, file_small, entity_resource)
          end
        rescue TemplateNotFoundError
          next
        end

        break unless path.nil?
      end
      break unless path.nil?
    end
    raise TemplateNotFoundError if path.nil?
  rescue TemplateNotFoundError
    if size.to_sym == :small
      size = :normal
      retry
    end
  end

  raise "Template not found for type, format: #{[entity_type, format] * ", "}" if path.nil?
  
  layout = locals[:_layout]
  layout = false if locals[:_xhr] and layout.nil?
  layout = true if layout.nil?

  renderer = Haml::Engine.new(path.read, :filename => path.find)

  case
  when (not layout)
    renderer.render(self, locals, &block)
  when (not block_given?)
    workflow_render("layout", nil, nil, locals) do 
      renderer.render(self, locals) 
    end
  else
    renderer.render(self, locals, &block)
  end
end

#followed_users(user) ⇒ Object



276
277
278
# File 'lib/rbbt/workflow/rest/helpers.rb', line 276

def followed_users(user)
  settings.followed_users[user] || []
end

#form_input(type, name, options = {}) ⇒ Object



179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
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
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
# File 'lib/rbbt/workflow/rest/helpers.rb', line 179

def form_input(type, name, options = {})
  id, label, hide, value, klass, default, description, input_options, array_separator = Misc.process_options options, 
    :id, :label, :hide, :value, :class, :default, :description, :input_options, :array_separator

  html_options ||= (input_options.nil? ? nil : input_options[:html_options]) || {}

  if id and not id.empty?
    str = "<div class='form_input' id='#{ id }'>"
  else
    str = "<div class='form_input'>"
  end

  array_separator ||= '|'
  label ||= name

  hide ||= html_options.delete :hidden

  if hide
    value = value * array_separator if Array === value

    html_options.merge! :id => id, 
      :type => 'hidden', 
      :name => name, 
      :value => value.to_s,
      :class  => [html_options[:class], klass].compact * " "

    str = "<input #{html_options_str(html_options)}/>" << "\n"
    return str
  end

  case type
  when :select
    str << "<label #{html_options_str({:for => id})}>"
    str << "<span class='input_name'>#{ label }</span>"
    str << ": <span class='input_description'>#{ description }</span>" if description
    str << "</label>" << "\n"

    str << "<select #{html_options_str(html_options.merge :name => name, :id => ((id and not id.empty?) ? "input_#{id}_select" : nil ))}>" << "\n"

    select_options = input_options.nil? ? nil : input_options[:select_options]
    if not select_options.nil?
      select_options.each do |option|
        option, option_name = option if Array === option
        option_name ||= option
        str << "<option #{html_options_str(html_options.merge :value => option, :selected => option.to_s == value.to_s)}>" << option_name.to_s << "</option>" << "\n"
      end
    end

    if html_options["attr-allow-empty"]
      str << "<option #{html_options_str(html_options.merge :value => "none", :selected => "none" == value.to_s)}>none</option>" << "\n"
    end

    str << "</select>" << "\n"
    str << "</div>"
    str
  when :boolean
    value = false if value == "false"
    default = value unless value.nil?
    default = false if default == "false"
    default = true if default == "true"

    check_true = default and %w(true yes y).include? default.to_s.downcase
    check_false = (default != nil and %w(false no n).include?(default.to_s.downcase))

    str << "<label #{"for='#{ id }'" if id}>"
    str << "<span class='input_name'>#{ label }</span>"
    str << "#{": <span class='input_description'>#{ description }</span>" if description}</label>" << "\n"

    str << "<input type='radio' #{check_true ? "checked=checked " : ""}#{html_options_str(html_options.merge :name => name, :value => 'true', :id => ((id and not id.empty?) ? "input_#{id}_true" : nil))}>" << "\n"
    str << "<label #{html_options_str(html_options.merge :for => ((id and not id.empty?) ? "input_#{id}_true" : nil), :class => [html_options[:class], 'radio_option radio_true'].compact * " ")}>true</label>" << "\n"

    str << "<input type='radio' #{check_false ? "checked=checked " : ""}#{html_options_str(html_options.merge :name => name, :value => 'false', :id => ((id and not id.empty?) ? "input_#{id}_false" : nil))}>" << "\n"
    str << "<label #{html_options_str(html_options.merge :for => ((id and not id.empty?) ? "input_#{id}_false" : nil), :class => [html_options[:class], 'radio_option radio_false'].compact * " ")}>false</label>" << "\n"
    str << "</div>"
    str
  when :string, :float, :integer
    value = value * array_separator if Array === value
    str << "<label #{"for='#{ id }'" if id}><span class='input_name'>#{ label }</span>#{": <span class='input_description'>#{ description }</span>" if description}#{": <span class='input_default'>(Default: #{ default })</span>" if default}</label>" << "\n"
    str << "<input #{html_options_str(html_options)} #{"class='#{klass ? klass : "#{ name } #{ type }" }'"} #{"id='#{ id }'" if id} name='#{ name }' #{"value='#{ value }'" if value}/>" << "\n"
    str << "</div>"
    str
  when :tsv, :array, :text
    str << "<label #{"for='#{ id }'" if id}><span class='input_name'>#{ label }</span>#{": <span class='input_description'>#{ description }</span>" if description}#{": <span class='input_default'>(Default: #{ default })</span>" if default}</label>" << "\n"
    str << "<p>"
    str << "<input #{html_options_str(html_options)} type='file' #{"class='#{klass ? klass : "#{ name } #{ type }" }'"} #{"id='input_#{ id }_tsv_file'" if id} name='#{ name }_param_file' #{"value='#{ value }'" if value}/>" << "\n"
    str << "<span class='tsv_textarea_note note'>(or use text area bellow)</span>"
    str << "</p>"
    str << "<textarea #{"class='#{klass ? klass : "#{ name } #{ type }" }'"} name='#{ name }' #{"id='input_#{ id }'" if id}>#{Array === value ? value * "\n" : value}</textarea>"
    str << "</div>"
    str
  end
end

#format_float(float) ⇒ Object



21
22
23
# File 'lib/rbbt/workflow/rest/helpers.rb', line 21

def format_float(float)
  "%.3f" % float
end

#html_options_str(html_options = {}) ⇒ Object



161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/rbbt/workflow/rest/helpers.rb', line 161

def html_options_str(html_options = {})
  return "" if html_options.nil? or html_options.empty?
  html_options.collect{|k,v| 
    case 
    when (k.nil? or v.nil? or (String === v and v.empty?))
      nil
    when String === v
      [k,"'" + v + "'"] * "="
    when Symbol === v
      [k,"'" + v.to_s + "'"] * "="
    when TrueClass === v
      [k,"'" + k.to_s + "'"] * "="
    else
      nil
    end
  }.compact * " "
end

#included(base) ⇒ Object



17
18
19
# File 'lib/rbbt/workflow/rest/helpers.rb', line 17

def included(base)
  base.include AnnotatedModule
end

Yields:

  • (f)


123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
# File 'lib/rbbt/workflow/rest/helpers.rb', line 123

def link_to_resource(filename = nil, text = nil, type = nil, options = {})
  case
  when filename.nil?
    filename = File.basename(TmpFile.tmp_file)
  when filename[0] == "."[0]
    extension = filename
    filename = File.basename(TmpFile.tmp_file) + extension
  end

  text ||= filename

  filename = Misc.sanitize_filename(filename)
  f = File.join(settings.file_dir, filename)
  FileUtils.mkdir_p(File.dirname(f))
  yield(f)

  type ||= :link
  case type
  when :image
    "<img src='/files/#{ filename }' class='file_resource'/>"
  when :link
    "<a href='/files/#{ filename }' class='file_resource'>#{ text }</a>"
  when :linked_image
    "<a href='/files/#{ filename }' class='file_resource' target='_blank'><img src='/files/#{ filename }' class='file_resource'/></a>"
  when :zoomable_image
    id = options[:id] || Misc.digest(filename)
    width, height= [300, 300]
    "<div class='zoomable_image'><img id='#{id}' style='width:#{width}px; height:#{height}px' rel='/files/#{ filename }' src='/files/#{ filename }' class='file_resource'/></div>"
  when :mapped_image
    mapid = options[:mapid] || options[:id] + '_map'
    width, height= [300, 300]
    mapfile = f.sub(/\.[^.]+$/, '.html')
    "<div class='mapped_image'>#{Open.read(mapfile)}<img class='has_map' usemap='##{mapid}' rel='/files/#{ filename }' src='/files/#{ filename }' class='file_resource'/></div>"
  else
    raise "Type not understood: #{ type }"
  end
end

#locate_file(*args) ⇒ Object



77
78
79
# File 'lib/rbbt/workflow/rest/render.rb', line 77

def locate_file(*args)
  RbbtHTMLHelpers.locate_file(*args)
end

#log(status, message) ⇒ Object



9
10
11
12
13
14
15
# File 'lib/rbbt/workflow/rest/helpers.rb', line 9

def log(status, message)
  if Step.log_relay_step
    Step.log_relay_step.log status, message
  else
    Log.warn "[#{ status }] #{ message }"
  end
end

#paginate(object, page = nil, just_keys = false) ⇒ Object



91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# File 'lib/rbbt/workflow/rest/render.rb', line 91

def paginate(object, page = nil, just_keys = false)
  return object unless TSV === object and not page.nil?

  return object if page == "all" or page.nil?
  field, num, size = parse_page(page)

  entity = Entity.formats[field]

  num = num.to_i
  size = size.to_i
  max = object.size / size + 1

  num = max if num > max
  num = - max if num < - max

  if entity and entity.respond_to? :tsv_sort
    object.page(num, size, field, just_keys, &entity.method(:tsv_sort))
  else
    object.page(num, size, field, just_keys)
  end
end

#parameter_controls(workflow = nil, values = {}, &block) ⇒ Object



102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/rbbt/workflow/rest/helpers.rb', line 102

def parameter_controls(workflow = nil, values = {}, &block)
  o = Object.new
  o.extend AnnotatedModule
  o.instance_eval &block

  inputs = o.inputs
  input_types = o.input_types
  input_defaults = o.input_defaults
  input_options = o.input_options

  hidden_inputs = []
  inputs.each do |input|
    if values[input].nil? and input_defaults.include? input
      values[input] = input_defaults[input]
    end
    hidden_inputs << input if input_options.include? input and input_options[input].delete :hide
  end

  workflow_partial('partials/_form', workflow, :hide_inputs => hidden_inputs, :inputs => inputs, :input_defaults => input_defaults, :input_options => input_options, :input_types => input_types, :values => values, :action => headers["AJAX-URL"], :klass => 'task', :method => 'get')
end

#parse_page(page) ⇒ Object



81
82
83
84
85
86
87
88
89
# File 'lib/rbbt/workflow/rest/render.rb', line 81

def parse_page(page)
  field, num, size = page.split("~").values_at 0, 1, 2
  if num.nil?
    num = field
    field = "key"
  end
  size ||= PAGESIZE
  [field, num, size]
end

#process_result(result, options) ⇒ Object



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
143
144
145
146
147
148
149
# File 'lib/rbbt/workflow/rest/render.rb', line 113

def process_result(result, options)
  rows = result

  if options.include? :_filter and not options[:_filter].nil?
    field, query = options[:_filter].split("~")

    entity = Entity.formats[field]

    if entity and entity.respond_to?(:filter)
      filter_proc = entity.method :filter
      if filter_proc.respond_to? :curry
        curried_proc = filter_proc.curry(query, field, options.merge(:tsv => result, :field => field))
      else
        curried_proc = Proc.new{|entity|
          filter_proc.call(query, field, options.merge(:tsv => result, :field => field), entity)
        }
      end
      rows = rows.select field => curried_proc
    else
      rows = rows.select field => Regexp.new(query)
    end
  end

  total = rows.size

  options[:_page] = "1" if rows.size > 100 and options[:_page].nil?
  if options.include?(:_page) and not options[:_page].nil?
    keys = paginate(rows, options[:_page], true)

    if keys
      rows = keys.zip(rows.values_at *keys)
    end

  end

  [rows, total]
end

#record_css(file) ⇒ Object



323
324
325
# File 'lib/rbbt/workflow/rest/helpers.rb', line 323

def record_css(file)
  @css_files << file
end

#record_js(file) ⇒ Object



280
281
282
# File 'lib/rbbt/workflow/rest/helpers.rb', line 280

def record_js(file)
  @js_files << file
end

#redirect_to_entity(entity, format, namespace) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/rbbt/workflow/rest/helpers.rb', line 25

def redirect_to_entity(entity, format, namespace)
  entity_type = Entity.formats[format]

  entity_options = []

  if defined? Organism and 
    entity_type.annotations.include? :organism and 
    ((String === namespace or Symbol === namespace) and 
     Organism.organisms.include? namespace.to_s or Organism.organisms.include? namespace.to_s.split("/").first)
    entity_options << ["organism", namespace] * "=" 
  end

  entity_options = entity_options.empty? ? "" : "?" + entity_options * "&"

  if format
    redirect "/entity/#{ entity_type.to_s }:#{ format }/#{ entity }#{entity_options}"
  else
    redirect "/entity/#{ entity_type.to_s }/#{ entity }#{entity_options}"
  end
end

#save_user_defaults(user, entity, action, params) ⇒ Object



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
# File 'lib/rbbt/workflow/rest/helpers.rb', line 68

def save_user_defaults(user, entity, action, params)
  key = [user, entity, action] * ":"
  clear = user_action_defaults.read_and_close do user_action_defaults[key] == :clear end

  if clear
    Log.debug("Effectively clearing user defaults for #{key}")
    user_action_defaults.write_and_close do
      user_action_defaults.delete key
    end
  else
    Log.debug("Saving user defaults for #{key}")
    user_action_defaults.write_and_close do
      begin
        hash = {}
        params.each{|k,v| hash[k.to_s.dup] = v.to_s.dup}
        user_action_defaults[key.to_s.dup] = hash
      rescue
        Log.warn($!.message)
        Log.warn("Error saving user defaults: #{[user, entity, action, params.inspect] * ", "}. Erasing")
        user_action_defaults.delete key.dump
        raise "Error saving default parameters. Cleared. Try reloading the page"
      end
    end
  end
end

#serve_cssObject



327
328
329
330
331
332
333
334
# File 'lib/rbbt/workflow/rest/helpers.rb', line 327

def serve_css
  res = @css_files.collect{|file|
    file += '.css' unless file =~ /.css$/
    "<link href='#{file}' rel='stylesheet' type='text/css' />"
  } * "\n"
  @css_files.clear
  res
end

#serve_js(compress = true) ⇒ Object



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
# File 'lib/rbbt/workflow/rest/helpers.rb', line 284

def serve_js(compress = true)
  res = if production? and compress

    md5 = Misc.digest(@js_files * ",")
    filename = File.join(settings.file_dir, "all_js-#{md5}.js")

    if not File.exists?(filename)
      text = @js_files.collect{|file| 
        file += '.js' unless file =~ /.js$/
        if file =~ /^\/js\/entity\/(.*?)\/(.*?)\/(.*)/
          entity_type, format = $1.split ":"
          entity = setup_entity(entity_type, format, $2)
          path = locate_file(WorkflowREST.workflows.last, nil, File.join("js", $3), entity)
        else
          path = begin
                   locate_file(WorkflowREST.workflows.last, nil, file.sub(/^\//,'')).find
                 rescue
                   locate_file(WorkflowREST.workflows.last, nil, File.join('public', file)).find
                 end
        end
        Open.read(path)
      } * "\n"


      FileUtils.mkdir_p File.dirname(filename) unless File.exists? File.dirname(filename)
      Open.write(filename, YUI::JavaScriptCompressor.new(:munge => false).compress(text))
    end

    "<script src='/files/#{File.basename(filename)}' type='text/javascript'></script>"
  else
    @js_files.collect{|file|
      file += '.js' unless file =~ /.js$/
        "<script src='#{ file }' type='text/javascript'></script>"
    } * "\n"
  end
  @js_files.clear
  res
end

#setup_entity(entity_type, format, entity, locals = {}) ⇒ Object



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
# File 'lib/rbbt/workflow/rest/render.rb', line 274

def setup_entity(entity_type, format, entity, locals = {})
  entity_class = case
                 when Entity.formats.include?(format)
                   Entity.formats[format] 
                 when Entity.formats.include?(entity_type)
                   Entity.formats[entity_type] 
                 else
                   nil
                 end

  if entity_class
    entity_class.setup(entity, *locals.values_at(*entity_class.annotations).collect{|v| 
      case v
      when "false"
        false
      when "true"
        true
      else
        v
      end
    })
    entity.format = format if entity.respond_to? :format
  end

  entity
end

#table(rows, header = nil, options = {}) ⇒ Object



272
273
274
# File 'lib/rbbt/workflow/rest/helpers.rb', line 272

def table(rows, header = nil, options = {}) 
  workflow_partial('partials/_table', StudyExplorer, nil, options.merge(:rows => rows, :header => header))
end

#user_action_defaultsObject



46
47
48
# File 'lib/rbbt/workflow/rest/helpers.rb', line 46

def user_action_defaults
  @@user_action_defaults ||= Persist.open_tokyocabinet(settings.user_action_defaults, false, :marshal)
end

#workflow_partial(file, *args) ⇒ Object



200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/rbbt/workflow/rest/render.rb', line 200

def workflow_partial(file, *args)
  locals = Hash === args.last ? args.pop : {}

  case args.length
  when 0
    workflow = locals[:workflow]
    task = locals[:task]
  when 1
    workflow = args.shift
    task = locals[:task]
  when 2
    workflow = args.shift
    task     = args.shift
  end

  workflow_render(file, workflow, task, locals.merge(:_layout => false))
end

#workflow_render(file, *args, &block) ⇒ Object



151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/rbbt/workflow/rest/render.rb', line 151

def workflow_render(file, *args, &block)
  locals = Hash === args.last ? args.pop : {}

  case args.length
  when 0
    workflow = locals[:workflow]
    task = locals[:task]
  when 1
    workflow = args.shift
    task = locals[:task]
  when 2
    workflow = args.shift
    task     = args.shift
  end

  size = locals.delete(:_size) || locals.delete("_size") || :normal

  case size.to_sym
  when :normal
    path = locate_file(workflow, task, file)
  when :small
    begin
      path = locate_file(workflow, task, file + '.small')
    rescue
      Log.debug $!.message
      path = locate_file(workflow, task, file)
    end
  end

  layout = locals[:_layout]
  layout = false if locals[:_xhr] and layout.nil?
  layout = true if layout.nil?

  locals = Misc.add_defaults locals, :workflow => workflow, :task => task

  renderer = Haml::Engine.new(path.read, :filename => path.find)

  case
  when (not layout)
    renderer.render(self, locals, &block)
  when (not block_given?)
    workflow_render("layout", workflow, task, locals) do 
      renderer.render(self, locals)
    end
  else
    renderer.render(self, locals, &block)
  end
end

#workflow_render_result(result, *args) ⇒ Object



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
# File 'lib/rbbt/workflow/rest/render.rb', line 218

def workflow_render_result(result, *args)
  options = Hash === args.last ? args.pop : {}


  case args.length
  when 0
    workflow = options[:workflow]
    task = options[:task]
  when 1
    workflow = args.shift
    task = options[:task]
  when 2
    workflow = args.shift
    task     = args.shift
  end


  format = options[:_format]
  page = options[:_page]

  # This part might be redundant!!!!
  case 
  when format.to_sym == :raw
    content_type "text/plain"
    case
    when options[:result_type] == :annotations
      Annotated.tsv(result, :all).to_s
    when Array === result
      result * "\n"
    else
      result.to_s
    end
  when format.to_sym == :json
    content_type "application/json"

    case
    when TSV === result
      result = paginate(result, page)
      result.dup.to_json
    when options[:result_type] == :annotations
      Annotated.json(result, true)
    else
      result.to_json
    end

    # This might be the only actual option
  when format.to_sym == :html
    content_type "text/html"
    options = Misc.add_defaults options, workflow.task_info(task)
    options = Misc.add_defaults options, :result => result, :workflow => workflow, :task => task
    workflow_render("result", workflow, task, options)
  else
    raise "Unkonwn format: #{format}"
  end
end