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

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

Instance Method Summary collapse

Instance Method Details

#componentsObject



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
# File 'lib/roda/plugins/component.rb', line 196

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 Gem::Specification.find_by_name("roda-component").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|
    if scope.request.env.include? 'HTTP_X_RODA_COMPONENT_ON_SERVER'
      data = JSON.parse scope.request.body.read
    else
      data = {}
    end

    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