Module: RbbtRESTHelpers

Defined in:
lib/rbbt/rest/common/misc.rb,
lib/rbbt/rest/common/cache.rb,
lib/rbbt/rest/common/forms.rb,
lib/rbbt/rest/common/table.rb,
lib/rbbt/rest/common/locate.rb,
lib/rbbt/rest/common/render.rb,
lib/rbbt/rest/common/resources.rb

Defined Under Namespace

Classes: Retry, TemplateMissing

Constant Summary collapse

PAGE_SIZE =
20
MEMORY_CACHE =
{}

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#javascript_resourcesObject

Returns the value of attribute javascript_resources.



2
3
4
# File 'lib/rbbt/rest/common/locate.rb', line 2

def javascript_resources
  @javascript_resources
end

#plugin_resourcesObject

Returns the value of attribute plugin_resources.



2
3
4
# File 'lib/rbbt/rest/common/locate.rb', line 2

def plugin_resources
  @plugin_resources
end

#sass_resourcesObject

Returns the value of attribute sass_resources.



2
3
4
# File 'lib/rbbt/rest/common/locate.rb', line 2

def sass_resources
  @sass_resources
end

#template_resourcesObject

Returns the value of attribute template_resources.



2
3
4
# File 'lib/rbbt/rest/common/locate.rb', line 2

def template_resources
  @template_resources
end

Class Method Details

.add_sass_load_path(path) ⇒ Object

{{{ SASS



56
57
58
# File 'lib/rbbt/rest/common/locate.rb', line 56

def self.add_sass_load_path(path)
  Sass::Engine::DEFAULT_OPTIONS[:load_paths].unshift path
end

.file_resourcesObject

{{{ TEMPLATE



33
34
35
# File 'lib/rbbt/rest/common/locate.rb', line 33

def self.file_resources
  @file_resources ||= template_resources
end

.javascript_resourcesObject

{{{ JAVASCRIPT



83
84
85
# File 'lib/rbbt/rest/common/locate.rb', line 83

def self.javascript_resources
  @javascript_resources ||= [Rbbt.share.views.public.find(:lib), Rbbt.share.views.public.js.find(:lib)]
end

.load_tsv(file) ⇒ Object



331
332
333
334
335
336
337
338
339
340
# File 'lib/rbbt/rest/common/table.rb', line 331

def self.load_tsv(file)
  tsv = TSV.open(Open.open(file))

  table_options = File.exists?(file + '.table_options') ? YAML.load_file(file + '.table_options') : {}
  tsv.entity_options = table_options[:tsv_entity_options]
  headers = table_options[:headers]
  headers.each{|field,p| tsv.entity_templates[field] = Misc.prepare_entity("TEMPLATE", p.first, (tsv.entity_options || {}).merge(p.last)) } unless headers.nil?

  [tsv, table_options]
end

.sass_resourcesObject



60
61
62
# File 'lib/rbbt/rest/common/locate.rb', line 60

def self.sass_resources
  @sass_resources ||= [Rbbt.share.views.compass.find(:lib)]
end

.save_tsv(tsv, path) ⇒ Object



314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
# File 'lib/rbbt/rest/common/table.rb', line 314

def self.save_tsv(tsv, path)
  Open.write(path, tsv.to_s)
  table_options = {:tsv_entity_options => tsv.entity_options}
  if tsv.entity_templates and tsv.entity_templates.any?
    table_options[:headers] ||= {}
    tsv.entity_templates.each do |field,template|
      next if table_options[:headers].include? field
      info = template.info
      info.delete :format
      info.delete :annotation_types
      info.delete :annotated_array
      table_options[:headers][field] = [template.annotation_types.last.to_s, info]
    end
  end
  Open.write(path + '.table_options', table_options.to_yaml )
end

.template_resourcesObject

{{{ TEMPLATE



8
9
10
# File 'lib/rbbt/rest/common/locate.rb', line 8

def self.template_resources
  @template_resources ||= [Rbbt.share.views.find(:lib)]
end

Instance Method Details

#add_GET_param(url, param, value) ⇒ Object



225
226
227
228
229
230
231
# File 'lib/rbbt/rest/common/misc.rb', line 225

def add_GET_param(url, param, value)
  if url =~ /\?.+=/
    url + "&#{ param }=#{ value }"
  else
    url + "?#{ param }=#{ value }"
  end
end

#cache(name, params = {}, &block) ⇒ Object



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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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
143
144
145
146
147
148
149
150
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
# File 'lib/rbbt/rest/common/cache.rb', line 16

def cache(name, params = {}, &block)
  @cache_type ||= params.delete :cache_type if params[:cache_type]
  return yield if name.nil? or @cache_type.nil? or @cache_type == :none

  send_file = consume_parameter(:_send_file, params)

  # Setup Step
  
  check = [params[:_template_file]].compact
  check += consume_parameter(:_cache_check, params) || []
  check.flatten!
  
  orig_name = name
  name += "_" << Misc.hash2md5(params) if params.any?

  path = params[:cache_file] || settings.cache_dir[name].find
  task = Task.setup(:name => orig_name, :result_type => :string, &block)

  step = Step.new(path, task, nil, nil, self)

  halt 200, step.info.to_json if @format == :info

  self.instance_variable_set("@step", step)

  if @file
    send_file step.file(@file), :filename => @file
  end

  # Clean/update job

  if old_cache(step.path, check) or update == :reload
    begin
      pid = step.info[:pid] 
      step.abort if pid and Misc.pid_exists?(pid) and not pid == Process.pid
      step.pid = nil
    rescue Exception
      Log.medium{$!.message}
    end
    step.clean 
  end

  clean_url = request.url
  clean_url = remove_GET_param(clean_url, :_update)
  clean_url = remove_GET_param(clean_url, :_)

  class << step; def url; @url; end; end
  step.instance_variable_set(:@url, clean_url)

  # Issue
  if not step.started?
    if cache_type == :synchronous or cache_type == :sync
      step.run 
    else
      step.fork
      step.soft_grace
    end
  end

  # Return fragment

  if @fragment
    fragment_file = step.file(@fragment)
    if File.exists?(fragment_file)
      case @format.to_s
      when "table"
        halt 200, tsv2html(fragment_file)
      when "json"
        halt 200, tsv_process(load_tsv(fragment_file).first).to_json
      when "tsv"
        content_type "text/tab-separated-values"
        halt 200, tsv_process(load_tsv(fragment_file).first).to_s
      when "values"
        tsv = tsv_process(load_tsv(fragment_file).first)
        list = tsv.values.flatten
        content_type "application/json" 
        halt 200, list.compact.to_json
      when "entities"
        orig_tsv = load_tsv(fragment_file).first
        tsv = tsv_process(orig_tsv)
        list = tsv.values.flatten
        tsv.prepare_entity(list, tsv.fields.first, tsv.entity_options)
        type = list.annotation_types.last
        list_id = "List of #{type} in table #{ @fragment }"
        list_id << " (#{ @filter })" if @filter
        Entity::List.save_list(type.to_s, list_id, list, user)
        header "Location", Entity::REST.entity_list_url(list_id, type)
        url = Entity::REST.entity_list_url(list_id, type)
        url = url + '?_layout=false' unless @layout
        redirect to(url)
      when "map"
        tsv = tsv_process(load_tsv(fragment_file).first)
        type = tsv.keys.annotation_types.last
        column = tsv.fields.first
        map_id = "Map #{type}-#{column} in #{ @fragment }"
        map_id << " (#{ @filter.gsub(';','|') })" if @filter
        Entity::Map.save_map(type.to_s, column, map_id, tsv, user)
        url = Entity::REST.entity_map_url(map_id, type, column)
        url = url + '?_layout=false' unless @layout
        redirect to(url)
      when "excel"
        require 'rbbt/tsv/excel'
        tsv = load_tsv(fragment_file).first
        content_type "text/html"
        data = nil
        excel_file = TmpFile.tmp_file
        tsv.excel(excel_file, :sort_by => @excel_sort_by, :sort_by_cast => @excel_sort_by_cast, :name => true)
        send_file excel_file, :type => 'application/vnd.ms-excel', :filename => 'table.xls'
      else
        send_file fragment_file
      end
    else
      if File.exists?(fragment_file + '.error') 
        klass, _sep, message = Open.read(fragment_file + '.error').partition(": ")
        raise Kernel.const_get(klass), message || "no message"
        #halt 500, html_tag(:span, File.read(fragment_file + '.error'), :class => "message") + 
        #  html_tag(:ul, File.read(fragment_file + '.backtrace').split("\n").collect{|l| html_tag(:li, l)} * "\n", :class => "backtrace") 
      else
        halt 202, "Fragment not completed"
      end
    end
  end

  if update == :reload
    redirect to(clean_url)
  end

  # Monitor
  
  begin

    if step.done?
      case
      when @permalink
        redirect to(permalink(step.path))
      when send_file
        send_file step.path
      else
        step.load
      end
    else

      case step.status
      when :error, :aborted
        error_for step, !@ajax

      else
        # check for problems
        begin
          check_step step
        rescue Aborted
          raise RbbtRESTHelpers::Retry
        end

        #if File.exists?(step.info_file) and Time.now - File.atime(step.info_file) > 60
        #  Log.debug{ "Checking on #{step.info_file}" }
        #  running = (not step.done?) and step.running?
        #  if FalseClass === running
        #    Log.debug{ "Aborting zombie #{step.info_file}" }
        #    step.abort unless step.done?
        #    raise RbbtRESTHelpers::Retry
        #  end
        #  FileUtils.touch(step.info_file)
        #end

        wait_on step, false
      end
    end
  rescue RbbtRESTHelpers::Retry
    retry
  end
end

#check_step(step) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/rbbt/rest/common/misc.rb', line 6

def check_step(step)
  if File.exists?(step.info_file) and Time.now - File.atime(step.info_file) > 60
    Log.debug{ "Checking on #{step.info_file}" }
    running = (not step.done?) and step.running?
    if FalseClass === running
      if step.done?
        Log.debug{ "Not aborting zombie #{step.info_file}: it is done" }
      else
        Log.debug{ "Aborting zombie #{step.info_file}" }
        step.abort 
        raise Aborted, "Zombie job aborted"
      end
    end
    FileUtils.touch(step.info_file)
  end
end

#consume_parameter(parameter, params = nil) ⇒ Object



110
111
112
113
114
115
116
117
118
119
# File 'lib/rbbt/rest/common/misc.rb', line 110

def consume_parameter(parameter, params = nil)
  params = self.params if params.nil?

  val = params.delete(parameter.to_sym) 
  val = params.delete(parameter.to_s) if val.nil?

  val = nil if String === val and val.empty?

  val
end

#development?Boolean

Returns:

  • (Boolean)


33
34
35
# File 'lib/rbbt/rest/common/misc.rb', line 33

def development?
  ENV["RACK_ENV"] == "develoment"
end

#error_for(job, layout = nil) ⇒ Object



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

def error_for(job, layout = nil)
  if ex = job.info[:exception]
    klass = ex[:class]
    msg = ex[:message]
    bkt = ex[:backtrace]
  else
    klass = "Exception"
    msg = job.messages[-1]
    bkt = []
  end

  code = klass.to_s == "ParameterException" ? 400 : 500
  case @format
  when :json
    halt code, {"message" => msg, "backtrace" => bkt}.to_json
  when :html
    layout = @layout if layout.nil?
    layout_file = (layout ? locate_template('layout') : nil)
    template_file = locate_template('error')

    result = render template_file, {:job => job}, layout_file

    halt code, result
  else
    content_type :text
    halt code, "#{klass}: " << msg << "\nBacktrace: " << bkt * "\n"
  end
end

#file_or_text_area(id, name, value, tsv = false) ⇒ Object



18
19
20
21
22
23
24
# File 'lib/rbbt/rest/common/forms.rb', line 18

def file_or_text_area(id, name, value, tsv = false)
  text_area_string = tsv ? "or use the text area below (you may use ',' intead of tabs)" : "or use the text area below"

  html_tag("input", nil, :type => "file", :id => (id.nil? ? nil : id +  "__" + "param_file"), :name => name.to_s + "__" + "param_file") + 
  html_tag("span", text_area_string, :class => "file_or_text_area") + 
  html_tag("textarea", value || "" , :name => name, :id => id )
end

#file_resourcesObject



37
38
39
# File 'lib/rbbt/rest/common/locate.rb', line 37

def file_resources
 [Rbbt.www.views] + RbbtRESTHelpers.file_resources
end

#filter(field, type = :string) ⇒ Object



309
310
311
312
# File 'lib/rbbt/rest/common/table.rb', line 309

def filter(field, type = :string)
  @table_filters ||= {}
  @table_filters[field] = type
end

#fix_input(type, value, param_file = nil) ⇒ Object



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
150
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
# File 'lib/rbbt/rest/common/misc.rb', line 121

def fix_input(type, value, param_file = nil)
  case type

  when nil, :string, :select
    value

  when :integer
    value.to_i

  when :float
    value.to_f

  when :multiple
    value.keys

  when :boolean
    param2boolean(value)

  when :text, :file
    if param_file and (value.nil? or (String === value and value.empty?))
      param_file[:tempfile].read
    else
      case value
      when String
        value.gsub(/\r\n/, "\n")
      when File, IO
        value
      when Hash
        value[:tempfile]
      else
        raise "Missing class for #{ type }: #{ Misc.fingerprint value }"
      end
    end

  when :array
    text = if param_file and (value.nil? or (String === value and value.empty?))
             param_file[:tempfile].read
           else
             value
           end

    case
    when Array === text
      text
    when text =~ /^list:([^:]+):(.+)$/
      Entity::List.load_list($1, $2, user)
    when text =~ /^\[.*\]$/sm
      JSON.parse(text)
    when text =~ /\n/
      text.split(/\r?\n/).collect{|l| l.strip}
    when text =~ /\|/
      text.split(/\|/).collect{|l| l.strip}
    when IO === text
      text
    when Hash === text
      io = text[:tempfile].open
      class << io
        attr_accessor :filename
      end
      io.filename = text[:filename]
      io
    else
      text.split(/,/).collect{|l| l.strip}
    end

  when :tsv
    if param_file and (value.nil? or (String === value and value.empty?))
      TSV.open(param_file[:tempfile].open)
    else
      TSV.open(StringIO.new(value), :sep=>/\t|,/)
    end
  end
end

#form_input(name, type, default = nil, current = nil, description = nil, id = nil, extra = {}) ⇒ Object



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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
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
# File 'lib/rbbt/rest/common/forms.rb', line 26

def form_input(name, type, default = nil, current = nil, description = nil, id = nil, extra = {})
  html_options = consume_parameter(:html_options, extra) || {}

  no_file = extra[:no_file] if extra

  case type
  when :multiple
    choices = consume_parameter(:choices, extra)
    default = default.collect{|o| o.to_s} if default
    current = current.collect{|o| o.to_s} if current
    input_label(id, name, description, Array === default ? default * ", " : nil, extra) +
      choices.collect do |choice|
        choice_name = name.to_s + "[#{ choice }]"
      
        check_true = (current && current.include?(choice.to_s)) || (default && default.include?(choice.to_s))

        check_true = false if check_true.nil?
          check_false = ! check_true
          
          choice_id = id + "[#{ Misc.snake_case(choice) }]"
          if id
            false_id = choice_id + '_false'
            true_id  = choice_id + '_true'
          else
            false_id = nil
            true_id = nil
          end

            choice_html = html_tag("input", nil, :type => :checkbox, :checked => check_true, :name => choice_name, :value => "true", :id => choice_id) +
              input_label(choice_id, choice, choice, nil, extra.merge({:class => :inline})) 

            html_tag('span', choice_html, :class => 'choice')
        end * "\n"


  when :boolean
    current = param2boolean(current) unless current.nil?
    default = param2boolean(default) unless default.nil?

    check_true = current.nil? ? default : current
    check_true = false if check_true.nil?
    check_false = ! check_true
    
    if id
      false_id = id + '__' << 'false'
      true_id = id + '__' << 'true'
    else
      false_id = nil
      true_id = nil
    end

    input_label(id, name, description, default, extra) +
      html_tag("input", nil, :type => :checkbox, :checked => check_true, :name => name, :value => "true", :id => id) +
      html_tag("input", nil, :type => :hidden, :name => name.to_s + "_checkbox_false", :value => "false") 

  when :string, :float, :integer, :hidden
    value = current.nil?  ? default : current

    input_type = case type
                 when :string
                   "text"
                 when :hidden
                   "hidden"
                 else
                   "number"
                 end

    step = case type
           when :string
             nil
           when :float
             "any"
           when :integer
             1
           end

    input_label(id, name, description, default, extra) +
    html_tag("input", nil, html_options.merge(:type => input_type, :name => name, :value => value, :id => id, :step => step))

  when :tsv, :array, :text, :file
    value = current.nil? ? default : current
    value = value * "\n" if Array === value

    if no_file
      input_label(id, name, description, nil, extra) +
        html_tag("textarea", value || "" , :name => name, :id => id )
    else
      input_label(id, name, description, nil, extra) +
        file_or_text_area(id, name, value, type == :tsv)
    end

  when :select
    value = current.nil? ? default : current

    allow_empty = consume_parameter :allow_empty, extra
    select_options = consume_parameter :select_options, extra
    
    if select_options 
      options = select_options.collect do |option|
        option, option_name = option if Array === option
        option_name = option if option_name.nil?
        html_tag('option', option_name, :value => option, :selected => option.to_s == value.to_s)
      end 
    else
      options = []
    end

    options.unshift html_tag('option', 'none', :value => 'none', :selected => value.to_s == 'none') if allow_empty

    input_label(id, name, description, default, extra) +
      html_tag('select', options * "\n", html_options.merge(:name => name, :id => id, "attr-selected" => (value ? value.to_s : "")))
  else
    "<span> Unsupported input #{name} #{type} </span>"
  end
end

#fragment(link = nil, &block) ⇒ Object



95
96
97
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
143
144
145
146
147
148
149
150
151
152
153
154
155
# File 'lib/rbbt/rest/common/render.rb', line 95

def fragment(link = nil, &block)
  fragment_code, link = [link.to_s, nil] if link and not link.to_s[0] == '<'
  text = fragment_code if fragment_code

  if block_given?
    if defined? @step and (@cache_type == :asynchronous or @cache_type == :async)

      fragment_code ||= (rand * 100000).to_i.to_s
      fragment_file = @step.file(fragment_code)

      pid = @step.child{
        begin
          res = capture_haml &block
          Open.write(fragment_file, res)
          Log.low("Fragment done: #{ fragment_file }")
        rescue Exception
          Open.write(fragment_file + '.error', [$!.class.to_s, $!.message] * ": ")
          Open.write(fragment_file + '.backtrace', $!.backtrace * "\n") if $!.backtrace
          Log.error("Error in fragment: #{ fragment_file }")
          Log.exception $!
          Kernel.exit! -1
        end
        Kernel.exit! 0
      }

      url = request.fullpath
      url = remove_GET_param(url, "_update")
      url = remove_GET_param(url, "_")
      fragment_url = add_GET_param(url, "_fragment", fragment_code)
      if link.nil?
        html_tag('a', "", :href => fragment_url, :class => 'fragment', "data-text" => text)
      else
        if link =~ / href=/
          link = link.sub(/ href=('|")/," href='#{fragment_url}'")
        else
          link = link.sub(/<a /,"<a href='#{fragment_url}' ")
        end

        if text
          link.sub(/<a /,"<a data-text='#{text}' ")
        else
          link
        end
      end
    else
      capture_haml &block
    end
  else
    if link =~ / class=/
      link = link.sub(/ class=('|")/,' class=\1fragment ')
    else
      link = link.sub(/<a /,'<a class="fragment" ')
    end
    
    if text
      link.sub(/<a /,"<a data-text='#{text}' ")
    else
      link
    end
  end
end

#hash2dl(hash, options = {}) ⇒ Object



233
234
235
236
237
238
239
240
# File 'lib/rbbt/rest/common/misc.rb', line 233

def hash2dl(hash, options = {})
  entries = hash.collect{|k,v|
    v = v * ", " if Array === v
    html_tag(:dt, k) +
    html_tag(:dd, v)
  } * "\n"
  html_tag(:dl, entries, options)
end

#header(field, entity_type, entity_options = {}) ⇒ Object



304
305
306
307
# File 'lib/rbbt/rest/common/table.rb', line 304

def header(field, entity_type, entity_options = {})
  @table_headers ||= {}
  @table_headers[field] = [entity_type, entity_options]
end

#html_tag(*args) ⇒ Object



217
218
219
# File 'lib/rbbt/rest/common/misc.rb', line 217

def html_tag(*args)
  Misc.html_tag(*args)
end

#input_label(id, name, description = nil, default = nil, options = {}) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/rbbt/rest/common/forms.rb', line 5

def input_label(id, name, description = nil, default = nil, options = {})
  options ||= {}
  text = consume_parameter :label, options

  if text.nil?
    text = name.to_s
    text += html_tag('span', " (default: " << default.to_s << ")", :class => 'input_default') unless default.nil?
  end

  label_id = id.nil? ? nil : 'label_for__' << id
  html_tag('label', text, {:id => label_id, :for => id, :title => description}.merge(options))
end


22
23
24
25
26
# File 'lib/rbbt/rest/common/resources.rb', line 22

def link_css(file)
  file += '.css' unless file =~ /.css$/
  file << "?_update=reload" if @debug_css
  html_tag('link', nil, :rel => 'stylesheet', :type => 'text/css', :href => file)
end


28
29
30
31
# File 'lib/rbbt/rest/common/resources.rb', line 28

def link_js(file)
  file += '.js' unless file =~ /.js$/
  html_tag('script', " ", :src => file, :type => 'text/javascript')
end

#load_tsv(file) ⇒ Object



347
348
349
# File 'lib/rbbt/rest/common/table.rb', line 347

def load_tsv(file)
  RbbtRESTHelpers.load_tsv(file)
end

#locate_file(file) ⇒ Object

Raises:



45
46
47
48
49
50
51
52
# File 'lib/rbbt/rest/common/locate.rb', line 45

def locate_file(file)
  file_resources.each do |resource|
    path = locate_file_from_resource(resource, file)
    return path if path.exists?
  end

  raise TemplateMissing, "File #{ file } not found"
end

#locate_file_from_resource(resource, file) ⇒ Object



41
42
43
# File 'lib/rbbt/rest/common/locate.rb', line 41

def locate_file_from_resource(resource, file)
  resource[file]
end

#locate_javascript(script) ⇒ Object

Raises:



98
99
100
101
102
103
104
105
# File 'lib/rbbt/rest/common/locate.rb', line 98

def locate_javascript(script)
  javascript_resources.each do |resource|
    path = locate_javascript_from_resource(resource, script)
    return path if path.exists?
  end

  raise TemplateMissing, "Script #{ script } not found"
end

#locate_javascript_from_resource(resource, script) ⇒ Object



92
93
94
95
96
# File 'lib/rbbt/rest/common/locate.rb', line 92

def locate_javascript_from_resource(resource, script)
  path = resource[script + '.js']
  return path if path.exists?
  resource[script]
end

#locate_sass(template) ⇒ Object

Raises:



72
73
74
75
76
77
78
79
# File 'lib/rbbt/rest/common/locate.rb', line 72

def locate_sass(template)
  sass_resources.each do |resource|
    path = locate_sass_from_resource(resource, template)
    return path if path.exists?
  end

  raise TemplateMissing, "Sass template #{ template } not found"
end

#locate_sass_from_resource(resource, template) ⇒ Object



68
69
70
# File 'lib/rbbt/rest/common/locate.rb', line 68

def locate_sass_from_resource(resource, template)
  resource[template + '.sass']
end

#locate_template(template) ⇒ Object

Raises:



20
21
22
23
24
25
26
27
28
29
# File 'lib/rbbt/rest/common/locate.rb', line 20

def locate_template(template)
  return Path.setup(template) if Open.exists?(template)
  return Path.setup(template+'.haml') if Open.exists?(template+'.haml')
  template_resources.each do |resource|
    path = locate_template_from_resource(resource, template)
    return path if path.exists?
  end

  raise TemplateMissing, "Template #{ template } not found"
end

#locate_template_from_resource(resource, template) ⇒ Object



16
17
18
# File 'lib/rbbt/rest/common/locate.rb', line 16

def locate_template_from_resource(resource, template)
  resource[template + '.haml']
end

#log(status, message = nil) ⇒ Object



25
26
27
28
29
30
31
# File 'lib/rbbt/rest/common/misc.rb', line 25

def log(status, message = nil)
  if @step
    @step.log(status, message)
  else
    Log.info{ "[#{ status }] #{ message }" }
  end
end


157
158
159
160
# File 'lib/rbbt/rest/common/render.rb', line 157

def modal_fragment(text, &block)
  link = "<a class='modal_fragment'>#{text}</a>"
  fragment(link, &block)
end

#old_cache(path, check) ⇒ Object



9
10
11
12
13
14
# File 'lib/rbbt/rest/common/cache.rb', line 9

def old_cache(path, check)
  return false if check.nil? or check.empty?
  return false if not File.exists? path
  check = [check] unless Array === check
  return check.select{|file| not File.exists?(file) or File.mtime(file) > File.mtime(path)}.any?
end

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



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
# File 'lib/rbbt/rest/common/table.rb', line 157

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?
  num, size, field = parse_page(page)


  if field and field[0] == "-"[0]
    field = field[1..-1]
    reverse = true
  else
    reverse = false
  end

  field =  CGI.unescapeHTML(Entity::REST.restore_element(field))

  if object.entity_templates[field]
    entity = object.entity_templates[field].annotation_types.last
  else
    entity = Entity.formats[field] 
  end

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

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

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

#param2boolean(value) ⇒ Object



206
207
208
209
210
211
212
213
214
215
# File 'lib/rbbt/rest/common/misc.rb', line 206

def param2boolean(value)
  case value
  when "true", "True", "TRUE", "T", "yes", "Yes", "y", "Y"
    true
  when "false", "False", "FALSE", "F", "no", "No", "N", "n"
    false
  else
    value
  end
end

#parse_page(page) ⇒ Object



146
147
148
149
150
151
152
153
154
155
# File 'lib/rbbt/rest/common/table.rb', line 146

def parse_page(page)
  num, size, field = page.split("~").values_at 0, 1, 2

  field, size = size, nil if field.nil?

  field = "key" if field.nil? or field.empty?
  size = PAGE_SIZE if size.nil? or size.empty?

  [num, size, field]
end

#partial_render(template, locals = {}, cache = nil, cache_options = {}) ⇒ Object



90
91
92
93
# File 'lib/rbbt/rest/common/render.rb', line 90

def partial_render(template, locals = {}, cache = nil, cache_options = {})
  template_file = locate_template(template)
  render(template_file, locals, nil, cache, cache_options)
end


242
243
244
245
246
247
248
# File 'lib/rbbt/rest/common/misc.rb', line 242

def permalink(path)
  id = Misc.digest(Time.now.to_s)
  dest = File.join(settings.permalink_dir, id)
  FileUtils.mkdir_p settings.permalink_dir unless File.exists? settings.permalink_dir
  FileUtils.ln_s(path, dest)
  "/permalink/#{ id }"
end

#prepare_input(params, input, type) ⇒ Object



195
196
197
198
199
200
201
202
203
# File 'lib/rbbt/rest/common/misc.rb', line 195

def prepare_input(params, input, type)
  value = consume_parameter(input, params)
  param_file = consume_parameter(input.to_s + '__param_file', params)
  return nil if value.nil? and param_file.nil?

  fixed_value = fix_input(type, value, param_file)

  fixed_value
end

#process_common_parametersObject



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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/rbbt/rest/common/misc.rb', line 41

def process_common_parameters
  @ajax = request.xhr?
  @ajax_url = headers["AJAX-URL"]

  @fullpath = request.fullpath

  @layout = consume_parameter(:_layout)

  @layout = false if @layout.nil? and     @ajax
  @layout = true  if @layout.nil? and not @ajax
  @layout = false if @layout == "false"
  @layout = true  if @layout == "true"

  @format = consume_parameter(:_format)
  @format = :html if @format.nil?
  @format = @format.to_sym if String === @format


  @size = consume_parameter(:_size)
  @size = @size.to_sym if String === @size

  @update = consume_parameter(:_update) unless @update
  @update = @update.to_sym if String === @update

  @profile = consume_parameter(:_profile) unless @profile
  @profile = @profile.to_sym if String === @profile

  @cache_type = consume_parameter(:_cache_type)
  @cache_type = @cache_type.to_sym if String === @cache_type

  @debug_js = consume_parameter(:_debug_js)
  @debug_js = false if @debug_js.nil? or @debug_js == "false"

  @debug_css = consume_parameter(:_debug_css)
  @debug_css = false if @debug_css.nil? or @debug_css == "false"

  @_ = consume_parameter(:_)

  @fragment = consume_parameter(:_fragment)
  @file     = consume_parameter(:_file)

  @excel_use_name     = consume_parameter(:_excel_use_name)
  @excel_sort_by      = consume_parameter(:_excel_sort_by)
  @excel_sort_by_cast = consume_parameter(:_excel_sort_by_cast)
  @excel_use_name = true if @excel_use_name.nil?

  @splat = consume_parameter :splat
  @captures = consume_parameter :captures

  # TSV table pagination, filtering, and slicing
  @page = consume_parameter :_page
  @filter = consume_parameter :_filter
  @column = consume_parameter :_column

  # Fix boolean inputs sumbitted using checkboxes
  params.keys.each do |param|
    if param =~ /(.*)_checkbox_false$/
      params[$1] = false if params[$1].nil?
      params.delete param
    end
  end

  @array_separator = consume_parameter(:_array_separator) || ','

  @permalink = consume_parameter :_permalink

  @clean_params = params.dup
end

#production?Boolean

Returns:

  • (Boolean)


37
38
39
# File 'lib/rbbt/rest/common/misc.rb', line 37

def production?
  settings.environment && settings.environment.to_s == 'production'
end

#record_css(file) ⇒ Object



18
19
20
# File 'lib/rbbt/rest/common/resources.rb', line 18

def record_css(file)
  recorded_css_files << file
end

#record_js(file) ⇒ Object



14
15
16
# File 'lib/rbbt/rest/common/resources.rb', line 14

def record_js(file)
  recorded_js_files << file
end

#recorded_css_filesObject



9
10
11
# File 'lib/rbbt/rest/common/resources.rb', line 9

def recorded_css_files
  @recorded_css_files ||= []
end

#recorded_js_filesObject



5
6
7
# File 'lib/rbbt/rest/common/resources.rb', line 5

def recorded_js_files
  @recorded_js_files ||= []
end

#remove_GET_param(url, param) ⇒ Object



221
222
223
# File 'lib/rbbt/rest/common/misc.rb', line 221

def remove_GET_param(url, param)
  url.gsub(/&?#{param}=[^&]+/,'').sub(/\?$/, '')
end

#render(template_file, locals = {}, layout_file = nil, cache = nil, cache_options = {}) ⇒ Object

Raises:



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/rbbt/rest/common/render.rb', line 52

def render(template_file, locals = {}, layout_file = nil, cache = nil, cache_options = {})
  raise TemplateMissing, "Template #{ template_file } not found" unless template_file.exists?
  raise TemplateMissing, "Template #{ layout_file } not found" unless layout_file.nil? or layout_file.exists?
  layout_file = layout_file.find if layout_file.respond_to? :find
  template_file = template_file.find if template_file.respond_to? :find
  if layout_file
    Tilt::HamlTemplate.new(layout_file, :filename => layout_file, :ugly => production?).render(self, locals) do
      Log.debug{ "Rendering #{template_file} with layout" }
      cache(cache, locals.merge(:_template_file => template_file, :user => user).merge(cache_options)) do
        Tilt::HamlTemplate.new(template_file, :filename => template_file, :ugly => production?).render(self, locals)
      end
    end
  else
    Log.debug{ "Rendering #{template_file} without layout" }
    cache(cache, locals.merge(:_template_file => template_file, :user => user).merge(cache_options)) do
      Tilt::HamlTemplate.new(template_file, :filename => template_file, :ugly => production?).render(self, locals)
    end
  end
end

#render_partial(template_file, locals = {}, cache = nil, cache_options = {}) ⇒ Object



79
80
81
# File 'lib/rbbt/rest/common/render.rb', line 79

def render_partial(template_file, locals = {}, cache = nil, cache_options = {})
  render(template_file, locals, nil, cache, cache_options)
end

#render_sass(file) ⇒ Object



72
73
74
75
76
77
# File 'lib/rbbt/rest/common/render.rb', line 72

def render_sass(file)
  renderer = Sass::Engine.new(Open.read(file), :filename => file, 
                              :style => production? ? :compressed : nil, 
                              :debug_info => development? ? true : false)
  renderer.render
end

#resource(filename = nil, text = nil, type = nil, options = {}) {|f| ... } ⇒ Object

Yields:

  • (f)


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/rest/common/render.rb', line 162

def 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 = settings.file_dir[filename].find
  FileUtils.mkdir_p(File.dirname(f))
  yield(f)

  type ||= :link
  case type
  when :image
    "<img src='/files/#{ filename }' alt='#{text}' 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= [600, 600]
    "<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

#reveal(text, id = nil, options = nil, &block) ⇒ Object



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

def reveal(text, id = nil, options = nil, &block)
  id ||= "rbbt_reveal_" << (rand * 10000).to_i.to_s

  content_html = capture_haml(&block)

  options = {} if options.nil?
  options = {:href => "#", "data-reveal-id" => 'modal1', 'attr-reveal_id' => id}.merge(options)
  options[:class] ||= ''
  options[:class] << ' rbbt_reveal_trigger'
  str = html_tag('a', text.to_s, options) << 
        "\n" <<
        html_tag('div', "\n" << content_html << "\n", :id => id, 'class' => 'rbbt_reveal_content') << 
        "\n"

  str
end

#save_tsv(file) ⇒ Object



342
343
344
# File 'lib/rbbt/rest/common/table.rb', line 342

def save_tsv(file)
  RbbtRESTHelpers.save_tsv(file)
end

#serve_cssObject



68
69
70
71
72
73
74
75
76
# File 'lib/rbbt/rest/common/resources.rb', line 68

def serve_css
  res = recorded_css_files.collect{|file|
    link_css(file)
  } * "\n"

  recorded_css_files.clear

  res
end

#serve_js(compress = true) ⇒ Object



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
# File 'lib/rbbt/rest/common/resources.rb', line 33

def serve_js(compress = true)
  if production? and compress and not @debug_js 
    md5 = Misc.digest(recorded_js_files * ",")
    filename = settings.file_dir["all_js-#{md5}.js"].find

    if not File.exists?(filename)
      Log.debug{ "Regenerating JS Compressed file: #{ filename }" }

      text = recorded_js_files.collect{|file| 
        begin
          path = locate_javascript(file)
        rescue
          path = locate_javascript(file.split("/")[2..-1] * "/")
        end

        Open.read(path)
      } * "\n"

      FileUtils.mkdir_p File.dirname(filename) unless File.exists? File.dirname(filename)
      Open.write(filename, Uglifier.compile(text))
    end

    res = "<script src='/files/#{File.basename(filename)}' type='text/javascript'></script>"
  else
    res = recorded_js_files.collect{|file|
      link_js(file)
    } * "\n"

  end

  recorded_js_files.clear

  res
end

#table(options = {}) ⇒ Object



351
352
353
354
355
356
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
# File 'lib/rbbt/rest/common/table.rb', line 351

def table(options = {})
  options = {} if options.nil?

  tsv = yield

  table_code = options[:table_id] || (rand * 100000).to_i.to_s
  table_code = Entity::REST.clean_element(table_code)
  table_code.sub!(/[^\w]/,'_')

  if @step
    table_file = @step.file(table_code) if @step

    url = add_GET_param(@fullpath, "_fragment", File.basename(table_file))
    url = remove_GET_param(url, "_update")
    url = remove_GET_param(url, "_layout")
    url = remove_GET_param(url, "_")
  end

  table_class = options[:table_class] || options[:class] || []
  table_class = [table_class] unless Array === table_class
  table_class << 'wide responsive' if tsv.fields.length > 4

  options[:url] = url
  options[:table_class] = table_class
  options[:tsv_entity_options] = tsv.entity_options

  if @table_headers and @table_headers.any?
    options[:headers] = @table_headers
    @table_headers = {}
  end

  if tsv.entity_templates and tsv.entity_templates.any?
    options[:headers] ||= {}
    tsv.entity_templates.each do |field,template|
      next if options[:headers].include? field
      next if template.nil?

      info = template.info
      info.delete :format
      info.delete :annotation_types
      info.delete :annotated_array

      options[:headers][field] = [template.annotation_types.last.to_s, info]
    end
  end

  if @table_filters and @table_filters.any?
    options[:filters] = @table_filters
    @table_filters = {}
  end

  if table_file
    Open.write table_file, tsv.to_s
    Open.write table_file + '.table_options', options.to_yaml if defined? options.any?

    total_size = tsv.size
    if options[:page].nil?  and total_size > PAGE_SIZE * 1.2
      @page = "1"
    else
      @page = options[:page]
    end
    tsv2html(table_file, options)
  else
    tsv2html(tsv, options)
  end
end

#table_value(value, type = nil, options = {}) ⇒ Object



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
# File 'lib/rbbt/rest/common/table.rb', line 278

def table_value(value, type = nil, options = {})
  options = {} if options.nil?
  return value.list_link :length, options[:list_id] if Array === value and options[:list_id] and value.respond_to? :list_link

  entity_options = options[:entity_options]

  Misc.prepare_entity(value, type, entity_options) if Entity.formats[type] and not options[:unnamed]

  value = value.link if value.respond_to? :link and not options[:unnamed]

  if Array === value and value.length > 100
    strip = value.length
    value = value[0..99]
  end

  res = if options[:span]
          Array === value ? value.collect{|v| "<span class='table_value'>#{v.to_s}</span>"} * ", " : "<span class='table_value'>#{value}</span>"
        else
          Array === value ? value.collect{|v| v.to_s} * ", " : value
        end

  res = "<span class='table_value strip'>[#{ strip } entries, 100 shown]</span>" + res if strip

  res
end

#template_render(template, locals = {}, cache = nil, cache_options = {}) ⇒ Object



83
84
85
86
87
88
# File 'lib/rbbt/rest/common/render.rb', line 83

def template_render(template, locals = {}, cache = nil, cache_options = {})
  template_file = locate_template(template)
  layout_file = @layout ? locate_template("layout") : nil

  render(template_file, locals, layout_file, cache, cache_options)
end

#tsv2html(file, default_table_options = {}) ⇒ Object



419
420
421
422
423
424
425
426
427
428
429
430
431
432
# File 'lib/rbbt/rest/common/table.rb', line 419

def tsv2html(file, default_table_options = {})
  if TSV === file
    tsv, table_options = file, {}
    table_options[:unnamed] = tsv.unnamed
  else
    tsv, table_options = load_tsv(file)
  end

  content_type "text/html"
  rows, length = tsv_rows(tsv)

  table_options = default_table_options.merge(table_options)
  partial_render('partials/table', {:total_size => length, :rows => rows, :header => tsv.all_fields, :table_options => table_options})
end

#tsv_process(tsv, filter = nil, column = nil) ⇒ Object



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
# File 'lib/rbbt/rest/common/table.rb', line 195

def tsv_process(tsv, filter = nil, column = nil)
  filter = @filter if filter.nil?
  column = @column if column.nil?

  if filter and filter.to_s != "false"
    filter.split(";;").each do |f|
      key, value = f.split("~")
      next if value.nil? or value.empty?
      value =  Entity::REST.restore_element(value)

      #invert
      if value =~ /^!\s*(.*)/
        value = $1
        invert = true
      else
        invert = false
      end

      #name
      if value =~ /^:name:\s*(.*)/
        value = $1
        name = true
      else
        name = false
      end

      if value =~ /^:length:\s*(.*)/
        value = $1
        length = true
      else
        length = false
      end

      if name
        old_tsv = tsv
        tsv = tsv.reorder(:key, key).add_field "NAME" do |k,values|
          NamedArray === values ? values[key].name : values.name
        end
        key = "NAME"
      end
      
      if length
        old_tsv = tsv
        tsv = tsv.reorder(:key, key).add_field "LENGTH" do |k,values|
          NamedArray === values ? values[key].length.to_s : values.length.to_s
        end
        key = "LENGTH"
      end
      
      case
      when value =~ /^([<>]=?)(.*)/
        tsv = tsv.select(key, invert){|k| k = k.first if Array === k; (k.nil? or (String === k and k.empty?)) ? false : k.to_f.send($1, $2.to_f)}
      when value =~ /^\/(.+)\/.{0,2}\s*$/
        tsv = tsv.select({key => Regexp.new($1)}, invert)
      when (value =~ /^\d+$/ and tsv.type == :double or tsv.type == :flat)
        tsv = tsv.select({key => value.to_i}, invert)
      else
        tsv = tsv.select({key => value}, invert)
      end

      tsv = old_tsv.select(tsv.keys) if name or length

    end
  end


  tsv = tsv.column(column) if column and not column.empty?

  tsv
end

#tsv_rows(tsv, page = nil, filter = nil, column = nil) ⇒ Object



266
267
268
269
270
271
272
273
274
275
# File 'lib/rbbt/rest/common/table.rb', line 266

def tsv_rows(tsv, page = nil, filter = nil, column = nil)
  tsv = tsv_process(tsv, filter, column)
  length = tsv.size
  page = @page if page.nil?
  if page.nil? or page.to_s == "false"
    [tsv_rows_full(tsv), length]
  else
    [tsv_rows_full(paginate(tsv, page)), length]
  end
end

#tsv_rows_full(tsv) ⇒ Object



130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/rbbt/rest/common/table.rb', line 130

def tsv_rows_full(tsv)
  case tsv.type 
  when :single
    tsv.collect{|id, value| [id, value]}
  when :list
    key_field = tsv.key_field
    tsv.collect{|id, values| new_values = [id].concat(values); begin NamedArray.setup(new_values, values.fields, id, values.entity_options, values.entity_templates); new_values.fields = [key_field].concat values.fields end if values.respond_to? :fields; new_values }
  when :flat
    key_field = tsv.key_field
    tsv.collect{|id, values| [id, values]}
  when :double
    key_field = tsv.key_field
    tsv.collect{|id, value_lists| new_value_lists = [id].concat(value_lists); begin NamedArray.setup(new_value_lists, value_lists.fields, id, value_lists.entity_options, value_lists.entity_templates); new_value_lists.fields = ([key_field].concat value_lists.fields) end if value_lists.respond_to? :fields; new_value_lists }
  end
end

#wait_on(job, layout = nil) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/rbbt/rest/common/render.rb', line 35

def wait_on(job, layout = nil)
  3.times do
    raise RbbtRESTHelpers::Retry if job.done? or job.error?
    sleep 1
  end

  raise RbbtRESTHelpers::Retry if job.done? or job.error?

  layout = @layout if layout.nil?

  layout_file = (layout ? locate_template('layout') : nil)
  template_file = locate_template('wait')

  status 202
  render template_file, {:job => job}, layout_file
end