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

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

Instance Method Summary collapse

Instance Method Details

#components ⇒ Object



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

def components
  on self.class.component_assets_route_regex do |component, action|
    # Process the ruby code into javascript
    Opal::Processor.source_map_enabled = false

    opal = Opal::Server.new do |s|
      # Append the gems path
      s.append_path Dir.pwd
      s.append_path Gem::Specification.find_by_name("roda-component").gem_dir + '/lib'
      # s.append_path Gem::Specification.find_by_name("scrivener-cj").gem_dir + '/lib'
      # Append the path to the components folder
      s.append_path scope.component_opts[:path]

      s.main = 'application'
    end

    sprockets = opal.sprockets

    js = sprockets['roda/component'].to_s
    # Loop through and and convert all the files to javascript
    Dir[scope.component_opts[:path] + '/**/*.rb'].each do |file|
      file = file.gsub(scope.component_opts[:path] + '/', '')
      js << sprockets[file].to_s
    end
    # Set the header to javascript
    response.headers["Content-Type"] = 'application/javascript; charset=UTF-8'

    js
  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

    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