Class: Roda::Component

Inherits:
Object show all
Defined in:
lib/roda/component.rb,
lib/roda/component/dom.rb,
lib/roda/component/faye.rb,
lib/roda/component/faye.rb,
lib/roda/component/form.rb,
lib/roda/component/events.rb,
lib/roda/component/version.rb,
lib/roda/component/instance.rb,
lib/roda/component/form/validations.rb

Defined Under Namespace

Classes: DOM, Events, Faye, Form, Instance

Constant Summary collapse

VERSION =
"0.1.73"

Class Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data = false) ⇒ Component

Returns a new instance of Component.



101
102
103
# File 'lib/roda/component.rb', line 101

def initialize(data = false)
  self
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object



442
443
444
445
446
447
448
# File 'lib/roda/component.rb', line 442

def method_missing method, *args, &block
  if server? && scope.respond_to?(method, true)
    scope.send method, *args, &block
  else
    super
  end
end

Class Attribute Details

._nameObject

Returns the value of attribute _name.



139
140
141
# File 'lib/roda/component.rb', line 139

def _name
  @_name
end

._on_server_methodsObject

Returns the value of attribute _on_server_methods.



139
140
141
# File 'lib/roda/component.rb', line 139

def _on_server_methods
  @_on_server_methods
end

Class Method Details

.add_tmplObject

We need to save the oga dom and the raw html. the reason we ave the raw html is so that we can use it client side.



356
357
358
359
360
361
362
363
364
# File 'lib/roda/component.rb', line 356

def tmpl name, dom = false, remove = true
  if dom
    cache[:tmpl][name] = { dom: remove ? dom.remove : dom }
    cache[:tmpl][name][:html] = cache[:tmpl][name][:dom].to_html
    cache[:tmpl][name]
  elsif t = cache[:tmpl][name]
    DOM.new t[:html]
  end
end

.appObject

roda app method



341
342
343
# File 'lib/roda/component.rb', line 341

def app
  @_app ||= {}
end

.cacheObject

cache for class



321
322
323
324
325
326
327
328
329
# File 'lib/roda/component.rb', line 321

def cache
  unless @_cache
    @_cache ||= Roda::RodaCache.new
    @_cache[:tmpl] = {}
    @_cache[:server_methods] = []
  end

  @_cache
end

.comp_html(_html = false, &block) ⇒ Object

The html source



264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
# File 'lib/roda/component.rb', line 264

def comp_html _html = false, &block
  if server?
    if _html.is_a? String
      if _html[%r{\A./}]
        cache[:html] = File.read _html
      else
        cache[:html] = File.read "#{component_opts[:path]}/#{_html}"
      end
    else
      cache[:html] = yield
    end

    cache[:html] = cache[:html]
    cache[:dom]  = DOM.new(cache[:html])
  end
end

.comp_name(_name = nil) ⇒ Object



252
253
254
255
256
257
258
259
260
261
# File 'lib/roda/component.rb', line 252

def comp_name(_name = nil)
  return name_original unless _name

  @_name = _name.to_s

  if server?
    @_file_location = caller.first.split(':').first
    component_opts[:class_name][@_name] = self.to_s
  end
end

.comp_require(*names) ⇒ Object



281
282
283
284
285
# File 'lib/roda/component.rb', line 281

def comp_require *names
  @_comp_requires ||= []
  names.each { |n| @_comp_requires << n}
  @_comp_requires
end

.comp_requiresObject



164
165
166
# File 'lib/roda/component.rb', line 164

def comp_requires
  (@_comp_requires ||= []).uniq
end

.comp_setup(&block) ⇒ Object

setup your dom



304
305
306
# File 'lib/roda/component.rb', line 304

def comp_setup &block
  block.call cache[:dom] if server?
end

.component_optsObject

shortcut to comp opts



360
361
362
363
364
365
366
# File 'lib/roda/component.rb', line 360

def component_opts
  if client?
    $component_opts
  else
    super
  end
end

.eventsObject



308
309
310
# File 'lib/roda/component.rb', line 308

def events
  @_events ||= Events.new self, component_opts, false
end

.file_locationObject



141
142
143
# File 'lib/roda/component.rb', line 141

def file_location
  @_file_location
end

.HTML(raw_html) ⇒ Object



287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
# File 'lib/roda/component.rb', line 287

def HTML raw_html
  raw_html = raw_html.strip

  if raw_html[/\A<!DOCTYPE/] || raw_html[/\A<html/]
    Nokogiri::HTML(raw_html)
  else
    parsed_html = Nokogiri::HTML.fragment(raw_html)

    if parsed_html.children.length >= 1
      parsed_html.children.first
    else
      parsed_html
    end
  end
end

.method_missing(method, *args, &block) ⇒ Object



368
369
370
371
372
373
374
# File 'lib/roda/component.rb', line 368

def method_missing method, *args, &block
  if server? && app.respond_to?(method, true)
    app.send method, *args, &block
  else
    super
  end
end

.new(*args, &block) ⇒ Object



145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
# File 'lib/roda/component.rb', line 145

def new(*args, &block)
  obj = self.allocate
  obj.instance_variable_set :@_scope, args.shift

  # don't send any args if none are wanted
  if server?
    if obj.method(:initialize).parameters.length > 0
      obj.send :initialize, *args, &block
    else
      obj.send :initialize, &block
    end
  else
    obj.send :initialize, *args, &block
  end

  obj._initialize
  obj
end

.on(*args, &block) ⇒ Object



312
313
314
315
316
317
318
# File 'lib/roda/component.rb', line 312

def on *args, &block
  if args.first.to_s != 'server'
    events.on(*args, &block)
  else
    on_server(&block)
  end
end

.on_server(&block) ⇒ Object



176
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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/roda/component.rb', line 176

def on_server &block
  @_on_server_methods ||= []

  if server?
    m = Module.new(&block)

    yield

    m.public_instance_methods(false).each do |meth|
      @_on_server_methods << meth.to_s

      alias_method :"original_#{meth}", :"#{meth}"
      define_method "#{meth}" do |*args, &blk|
        o_name = "original_#{meth}"

        if method(o_name).parameters.length > 0
          result = send(o_name, *args, &block)
        else
          result = send(o_name, &block)
        end

        blk ? blk.call(result) : result
      end
    end
  else
    m = Module.new(&block)

    m.public_instance_methods(false).each do |meth|
      @_on_server_methods << meth.to_s

      define_method "#{meth}" do |*args, &blk|
        name     = self.class._name
        # event_id = "comp-event-#{$faye.generate_id}"

        HTTP.post("/components/#{name}/call/#{meth}",
          headers: {
            'X-CSRF-TOKEN' => Element.find('meta[name=_csrf]').attr('content'),
            'X-RODA-COMPONENT-ON-SERVER' => true
          },
          payload: args) do |response|

            # We set the new csrf token
            xhr  = Native(response.xhr)
            csrf = xhr.getResponseHeader('NEW-CSRF')
            Element.find('meta[name=_csrf]').attr 'content', csrf
            ###########################

            res = JSON.from_object(`response`)

            blk.call res[:body], res
        end

        # Element['body'].on event_id do |event, local, data|
        #   blk.call local, event, data
        # end
        #
        # $faye.publish("/components/outgoing/#{$faye.private_id}/#{$faye.public_id}", {
        #   name: name,
        #   type: 'event',
        #   event_type: 'call',
        #   event_method: meth,
        #   event_id: event_id,
        #   local: args.first || nil
        # })


        true
      end
    end

    include m
  end
end

.set_app(app) ⇒ Object

set the current roda app



332
333
334
335
336
337
338
# File 'lib/roda/component.rb', line 332

def set_app app
  begin
    @_app = app.respond_to?(:new) ? app.new : app
  rescue
    @_app = app.respond_to?(:new) ? app.new('') : app
  end
end

.set_tmplObject

We need to save the oga dom and the raw html. the reason we ave the raw html is so that we can use it client side.



357
358
359
360
361
362
363
364
365
# File 'lib/roda/component.rb', line 357

def tmpl name, dom = false, remove = true
  if dom
    cache[:tmpl][name] = { dom: remove ? dom.remove : dom }
    cache[:tmpl][name][:html] = cache[:tmpl][name][:dom].to_html
    cache[:tmpl][name]
  elsif t = cache[:tmpl][name]
    DOM.new t[:html]
  end
end

.tmpl(name, dom = false, remove = true) ⇒ Object

We need to save the oga dom and the raw html. the reason we ave the raw html is so that we can use it client side.



347
348
349
350
351
352
353
354
355
# File 'lib/roda/component.rb', line 347

def tmpl name, dom = false, remove = true
  if dom
    cache[:tmpl][name] = { dom: remove ? dom.remove : dom }
    cache[:tmpl][name][:html] = cache[:tmpl][name][:dom].to_html
    cache[:tmpl][name]
  elsif t = cache[:tmpl][name]
    DOM.new t[:html]
  end
end

Instance Method Details

#_initialize(scope = false) ⇒ Object



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

def _initialize(scope = false)
  @_scope = scope if scope

  if $faye && client? && !$component_opts[:faye][:"#{self.class._name}"]
    $component_opts[:faye][:"#{self.class._name}"] = true

    $faye.subscribe "/components/#{self.class._name}" do |msg|
      msg = Native(msg)

      trigger :"#{msg[:type]}", msg['local'], msg unless $faye.public_id == msg[:public_id]
    end

    $faye.on 'transport:up' do
      $faye.online = true

      if $faye.disconnected
        trigger :reconnect
      else
        trigger :connect
      end
    end

    $faye.on 'transport:down' do
      $faye.disconnected = true
      $faye.online       = false
      trigger :disconnect
    end

    self
  end

end

#cacheObject



387
388
389
# File 'lib/roda/component.rb', line 387

def cache
  @_cache ||= self.class.cache.dup
end

#component(name, options = {}, &block) ⇒ Object Also known as: comp, roda_component



451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
# File 'lib/roda/component.rb', line 451

def component name, options = {}, &block
  action  = options.delete(:call)
  trigger = options.delete(:trigger)
  js      = options.delete(:js)
  args    = options.delete(:args)

  comp = load_component name, options

  # call action
  # TODO: make sure the single method parameter isn't a block
  if trigger
    if args
      comp_response = comp.trigger trigger, *args
    else
      comp_response = comp.trigger trigger, options
    end
  elsif action
    # We want to make sure it's not a method that already exists in ruba
    # otherwise that would give us a false positive.
    if comp.methods.include? action
      comp_response = comp.send(action, options, &block)
    else
      fail "##{action} doesn't exist for #{comp.class}"
    end
  end

  if trigger || action
    comp_response
  else
    comp
  end
end

#component_optsObject



416
417
418
# File 'lib/roda/component.rb', line 416

def component_opts
  self.class.component_opts
end

#domObject Also known as: element



395
396
397
398
399
400
401
402
# File 'lib/roda/component.rb', line 395

def dom
  if server?
    # TODO: duplicate cache[:dom] so we don't need to parse all the html again
    @_dom ||= DOM.new(cache[:dom].dom.to_html)
  else
    @_dom ||= DOM.new(Element)
  end
end

#eventsObject



391
392
393
# File 'lib/roda/component.rb', line 391

def events
  @_events ||= Events.new self.class, component_opts, scope
end

#function(*args, &block) ⇒ Object



424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
# File 'lib/roda/component.rb', line 424

def function *args, &block
  args.any? && raise(ArgumentError, '`function` does not accept arguments')
  block || raise(ArgumentError, 'block required')
  proc do |*a|
    a.map! {|x| Native(`x`)}
    @this = Native(`this`)
    %x{
     var bs = block.$$s,
        result;
      block.$$s = null;
      result = block.apply(self, a);
      block.$$s = bs;
      
      return result;
    }
  end
end

#get_value_for(field, data) ⇒ Object



539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
# File 'lib/roda/component.rb', line 539

def get_value_for field, data
  field = (field || '').split '.'

  if field.length > 1
    value = data.is_a?(Hash) ? data.to_obj : data

    field.each_with_index do |f, i|
      # might not have the parent object
      if (value.respond_to?('empty?') ? value.empty? : !value.present?)
        value = ''
        next
      end

      if (i+1) < field.length
        begin
          value = value.send(f)
        rescue
          value = nil
        end
      else
        begin
          value = value.respond_to?(:present) ? value.present("print_#{f}") : value.send(f)
        rescue
          value = nil
        end
      end

    end
  else
    begin
      value = data.respond_to?(:present) ? data.present("print_#{field.first}") : data.send(field.first)
    rescue
      value = nil
    end
  end

  value
end

#indifferent_params(params) ⇒ Object

Recursively process the request params and convert hashes to support indifferent access, leaving other values alone.



581
582
583
# File 'lib/roda/component.rb', line 581

def indifferent_params(params)
  params.indifferent
end

#inherited(subclass) ⇒ Object



169
170
171
172
173
# File 'lib/roda/component.rb', line 169

def inherited(subclass)
  super
  # We want to set the app for all sub classes
  subclass.set_app app
end

#load_component(name, options = {}) ⇒ Object



487
488
489
490
# File 'lib/roda/component.rb', line 487

def load_component name, options = {}
  # component_opts[:comp][name] ||= component_opts[:class_name][name].split('::').inject(Object) {|o,c| o.const_get(c)}.new self, options
  component_opts[:comp][name][:class]
end

#render(*args, &block) ⇒ Object



585
586
587
# File 'lib/roda/component.rb', line 585

def render *args, &block
  display *args, &block
end

#render_fields(data, options = {}) ⇒ Object



492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
# File 'lib/roda/component.rb', line 492

def render_fields data, options = {}
  data = data.is_a?(Hash) ? data.to_obj : data

  l_dom = options[:dom] || dom

  l_dom.find("[data-if]") do |field_dom|
    value = get_value_for field_dom['data-if'], data

    unless value.present?
      field_dom.remove
    end
  end

  l_dom.find("[data-unless]") do |field_dom|
    value = get_value_for field_dom['data-unless'], data

    if value.present?
      field_dom.remove
    end
  end

  l_dom.find("[data-field]") do |field_dom|
    if field = field_dom['data-field']
      value = get_value_for field, data

      if !value.nil?
        value = value.to_s

        if value != value.upcase && !value.match(Roda::Component::Form::EMAIL)
          field_value = value.titleize
        else
          field_value = value
        end

        field_value = 'No'  if field_value == 'False'
        field_value = 'Yes' if field_value == 'True'

        field_dom.html = field_value
      else
        field_dom.html = ''
      end
    end
  end

  l_dom
end

#tmpl(name) ⇒ Object

Grab the template from the cache, use the nokogiri dom or create a jquery element for server side issue: can’t use the cached dom because duping doesn’t work.



408
409
410
411
412
413
414
# File 'lib/roda/component.rb', line 408

def tmpl name
  if t = cache[:tmpl][name]
    DOM.new t[:html]
  else
    false
  end
end

#trigger(*args) ⇒ Object



420
421
422
# File 'lib/roda/component.rb', line 420

def trigger *args
  events.trigger(*args)
end