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

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

Instance Method Summary collapse

Instance Method Details

#componentsObject



222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# File 'lib/roda/plugins/component.rb', line 222

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/]
      run opal.sprockets
    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
    data = body ? JSON.parse(body) : {}

    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