Module: Roda::RodaPlugins::Component::RequestMethods

Defined in:
lib/roda/plugins/component.rb

Instance Method Summary collapse

Instance Method Details

#componentsObject



239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
# File 'lib/roda/plugins/component.rb', line 239

def components
  opal = Opal::Server.new do |s|
    # Append the gems path
    if scope.component_opts[:debug]
      s.debug      = true
      s.source_map = true
    else
      s.source_map = false
    end

    # we are loading the source maps ourselves

    s.prefix = "/#{scope.component_opts[:assets_route]}"

    s.append_path Roda::Component.method(:comp_setup).source_location.first.sub('/roda/component.rb', '')
    s.append_path AbilityList.method(:version).source_location.first.sub('/ability_list.rb', '')
    # s.append_path Gem::Specification.find_by_name("ability_list").gem_dir + '/lib'

    # Append the path to the components folder
    s.append_path scope.component_opts[:path]

    s.main = 'roda/component'
  end

  on self.class.component_assets_route_regex do |component, action|
    path = scope.request.env['REQUEST_PATH']

    if path[/\.js\Z/]
      scope.response.headers["Content-Type"] = 'application/javascript; charset=UTF-8'
      scope.response.headers["Expires"] = (Time.now + 1.hour).utc.rfc2822
      p = path.sub('/assets/components/', '')
      $compiled_opal ||= {}
      $compiled_opal[p] ||= opal.sprockets[p].to_s
    elsif scope.component_opts[:debug]
      if path[/\.rb\Z/] && js_file = scope.request.env['PATH_INFO'].scan(/(.*\.map)/)
        scope.request.env['PATH_INFO'] = path.gsub(js_file.last.first, '').gsub("/#{scope.component_opts[:assets_route]}", '')
      end
      run Opal::SourceMapServer.new(opal.sprockets, path)
    end
  end

  on self.class.component_route_regex do |comp, type, action|
    body = scope.request.body.read

    begin
      data = body ? JSON.parse(body) : {}
    rescue
      data = {}
    end

    data.merge! scope.request.params unless data.is_a? Array

    if data.is_a? Array
      data = {args: data}
    end

    case type
    when 'call'
      data[:call] = action
    when 'trigger'
      data[:trigger] = action
    end

    res = scope.roda_component(comp, data)

    scope.response.headers["NEW-CSRF"] = scope.csrf_token

    if res.is_a? Hash
      scope.response.headers["Content-Type"] = 'application/json; charset=UTF-8'
      res = res.to_json
    else
      res = res.to_s
    end

    res
  end
end