Class: Card::Format

Inherits:
Object show all
Includes:
Wagn::Location
Defined in:
lib/card/format.rb

Constant Summary collapse

DEPRECATED_VIEWS =
{ :view=>:open, :card=>:open, :line=>:closed, :bare=>:core, :naked=>:core }
INCLUSION_MODES =
{ :closed=>:closed, :closed_content=>:closed, :edit=>:edit,
:layout=>:layout, :new=>:edit, :setup=>:edit, :normal=>:normal, :template=>:template }
@@max_char_count =

should come from Wagn.config

200
@@max_depth =

ditto

20
@@registered =
[]

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Wagn::Location

#discard_locations_for, #interrupted_action, #link_to_page, #location_history, #page_path, #previous_location, #save_interrupted_action, #save_location, #url_key_for_location, #wagn_path, #wagn_url

Constructor Details

#initialize(card, opts = {}) ⇒ Format

~~~~~ INSTANCE METHODS



78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/card/format.rb', line 78

def initialize card, opts={}
  @card = card or raise Card::Error, "format initialized without card"
  opts.each do |key, value|
    instance_variable_set "@#{key}", value
  end

  @mode  ||= :normal
  @depth ||= 0
  @root  ||= self      

  @context_names ||= if params[:slot] && context_name_list = params[:slot][:name_context]
    context_name_list.split(',').map &:to_name
  else [] end
    
  include_set_format_modules
  self
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *opts, &proc) ⇒ Object



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# File 'lib/card/format.rb', line 157

def method_missing method, *opts, &proc
  case method
  when /(_)?(optional_)?render(_(\w+))?/  
    view = $3 ? $4 : opts.shift      
    args = opts[0] ? opts.shift.clone : {} 
    args.merge!( :optional=>true, :default_visibility=>opts.shift) if $2
    args[ :skip_permissions ] = true if $1
    render view, args           
  when /^_view_(\w+)/
    view = @current_view || $1 
    unsupported_view view
  else
    proc = proc { |*a| raw yield *a } if proc
    response = root.template.send method, *opts, &proc
    String===response ? root.template.raw( response ) : response
  end
end

Instance Attribute Details

#cardObject (readonly)

Returns the value of attribute card.



19
20
21
# File 'lib/card/format.rb', line 19

def card
  @card
end

#error_statusObject

Returns the value of attribute error_status.



20
21
22
# File 'lib/card/format.rb', line 20

def error_status
  @error_status
end

#formObject

Returns the value of attribute form.



20
21
22
# File 'lib/card/format.rb', line 20

def form
  @form
end

#inclusion_optsObject

Returns the value of attribute inclusion_opts.



20
21
22
# File 'lib/card/format.rb', line 20

def inclusion_opts
  @inclusion_opts
end

#main_optsObject (readonly)

Returns the value of attribute main_opts.



19
20
21
# File 'lib/card/format.rb', line 19

def main_opts
  @main_opts
end

#parentObject (readonly)

Returns the value of attribute parent.



19
20
21
# File 'lib/card/format.rb', line 19

def parent
  @parent
end

#rootObject (readonly)

Returns the value of attribute root.



19
20
21
# File 'lib/card/format.rb', line 19

def root
  @root
end

Class Method Details

.extract_class_vars(view, opts) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/card/format.rb', line 36

def extract_class_vars view, opts
  return unless opts.present?
  perms[view]       = opts.delete(:perms)      if opts[:perms]
  error_codes[view] = opts.delete(:error_code) if opts[:error_code]
  denial_views[view]= opts.delete(:denial)     if opts[:denial]

  if tags = opts.delete(:tags)
    Array.wrap(tags).each do |tag|
      view_tags[view] ||= {}
      view_tags[view][tag] = true
    end
  end

end

.format_ancestryObject



65
66
67
68
69
70
71
# File 'lib/card/format.rb', line 65

def format_ancestry
  ancestry = [ self ]
  unless self == Card::Format
    ancestry = ancestry + superclass.format_ancestry
  end
  ancestry
end

.format_class_name(format) ⇒ Object



29
30
31
32
33
# File 'lib/card/format.rb', line 29

def format_class_name format
  f = format.to_s
  f = @@aliases[ f ] || f
  "#{ f.camelize }Format"
end

.new(card, opts = {}) ⇒ Object



51
52
53
54
55
56
57
58
# File 'lib/card/format.rb', line 51

def new card, opts={}
  if self != Format
    super
  else
    klass = Card.const_get format_class_name( opts[:format] || :html )
    self == klass ? super : klass.new( card, opts )
  end
end

.register(format) ⇒ Object



25
26
27
# File 'lib/card/format.rb', line 25

def register format
  @@registered << format.to_s
end

.tagged(view, tag) ⇒ Object



60
61
62
# File 'lib/card/format.rb', line 60

def tagged view, tag
  view and tag and view_tags = @@view_tags[view.to_sym] and view_tags[tag.to_sym]
end

Instance Method Details

#add_name_context(name = nil) ⇒ Object



542
543
544
545
546
# File 'lib/card/format.rb', line 542

def add_name_context name=nil
  name ||= card.name
  @context_names += name.to_name.part_names
  @context_names.uniq!
end


492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
# File 'lib/card/format.rb', line 492

def build_link href, text=nil
  opts = {:text => text }

  opts[:class] = case href.to_s
    when /^https?:/                      ; 'external-link'
    when /^mailto:/                      ; 'email-link'
    when /^([a-zA-Z][\-+.a-zA-Z\d]*):/   ; $1 + '-link'
    when /^\//
      href = internal_url href[1..-1]    ; 'internal-link'
    else
      return href
      Rails.logger.debug "build_link mistakenly(?) called on #{href}, #{text}"
    end
    
  final_link href, opts
end

#canonicalize_view(view) ⇒ Object



345
346
347
348
349
350
# File 'lib/card/format.rb', line 345

def canonicalize_view view
  unless view.blank?
    view_key = view.to_name.key.to_sym
    DEPRECATED_VIEWS[view_key] || view_key
  end
end


509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
# File 'lib/card/format.rb', line 509

def card_link name, text, known, type=nil
  text ||= name
  linkname = name.to_name.url_key
  opts = {
    :class => ( known ? 'known-card' : 'wanted-card' ),
    :text  => ( text.to_name.to_show @context_names  )
  }
  if !known
    link_params = {}
    link_params['name'] = name.to_s if name.to_s != linkname
    link_params['type'] = type      if type
    linkname += "?#{ { :card => link_params }.to_param }" if !link_params.empty?
  end
  final_link internal_url( linkname ), opts
end

#controllerObject



120
121
122
# File 'lib/card/format.rb', line 120

def controller
  Env[:controller] ||= CardController.new
end

#default_item_viewObject



467
468
469
# File 'lib/card/format.rb', line 467

def default_item_view
  :name
end

#default_render_args(view, a = nil) ⇒ Object



228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# File 'lib/card/format.rb', line 228

def default_render_args view, a=nil
  args = case a
  when nil   ; {}
  when Hash  ; a.clone
  when Array ; a[0].merge a[1]
  else       ; raise Card::Error, "bad render args: #{a}"
  end
  
  view_key = canonicalize_view view
  default_method = "default_#{ view }_args"
  if respond_to? default_method
    send default_method, args
  end
  args
end

#error_cardnameObject



256
257
258
# File 'lib/card/format.rb', line 256

def error_cardname
  card && card.name.present? ? card.name : 'unknown card'
end

#expand_main(opts) ⇒ Object



381
382
383
384
385
386
387
388
389
390
391
392
# File 'lib/card/format.rb', line 381

def expand_main opts
  opts.merge! root.main_opts if root.main_opts
  legacy_main_opts_tweaks! opts

  opts[:view] ||= :open
  with_inclusion_mode :normal do
    @mainline = true
    result = wrap_main nest( root.card, opts )
    @mainline = false
    result
  end
end

———— LINKS —————



484
485
486
487
488
489
490
# File 'lib/card/format.rb', line 484

def final_link href, opts
  if text = opts[:text]
    "#{text}[#{href}]"
  else
    href
  end
end

#focal?Boolean

meaning the current card is the requested card

Returns:

  • (Boolean)


140
141
142
143
144
145
146
# File 'lib/card/format.rb', line 140

def focal? # meaning the current card is the requested card
  if Env.ajax?
    @depth == 0
  else
    main?
  end
end

#format_date(date, include_time = true) ⇒ Object



533
534
535
536
537
538
539
540
# File 'lib/card/format.rb', line 533

def format_date date, include_time = true
  # Must use DateTime because Time doesn't support %e on at least some platforms
  if include_time
    DateTime.new(date.year, date.mon, date.day, date.hour, date.min, date.sec).strftime("%B %e, %Y %H:%M:%S")
  else
    DateTime.new(date.year, date.mon, date.day).strftime("%B %e, %Y")
  end
end

#get_inclusion_content(cardname) ⇒ Object



442
443
444
445
446
447
448
449
450
451
# File 'lib/card/format.rb', line 442

def get_inclusion_content cardname
  content = params[cardname.to_s.gsub(/\+/,'_')]

  # CLEANME This is a hack to get it so plus cards re-populate on failed signups
  if p = params['subcards'] and card_params = p[cardname.to_s]
    content = card_params['content']
  end
  content if content.present?  # why is this necessary? - efm  
                               # probably for blanks?  -- older/wiser efm
end

#get_inclusion_defaultsObject



112
113
114
# File 'lib/card/format.rb', line 112

def get_inclusion_defaults
  { :view => :name }
end

#hide_views(args) ⇒ Object



219
220
221
# File 'lib/card/format.rb', line 219

def hide_views args
  parse_view_visibility args[:hide]
end

#include_set_format_modulesObject



96
97
98
99
100
101
102
# File 'lib/card/format.rb', line 96

def include_set_format_modules
  self.class.format_ancestry.reverse.each do |klass|
    card.set_format_modules( klass ).each do |m|
      singleton_class.send :include, m
    end
  end
end

#inclusion_defaultsObject



104
105
106
107
108
109
110
# File 'lib/card/format.rb', line 104

def inclusion_defaults
  @inclusion_defaults ||= begin
    defaults = get_inclusion_defaults.clone
    defaults.merge! @inclusion_opts if @inclusion_opts
    defaults
  end
end

#internal_url(relative_path) ⇒ Object



529
530
531
# File 'lib/card/format.rb', line 529

def internal_url relative_path
  wagn_path relative_path
end

#legacy_main_opts_tweaks!(opts) ⇒ Object



394
395
396
397
398
399
400
401
402
# File 'lib/card/format.rb', line 394

def legacy_main_opts_tweaks! opts 
  if val=params[:size] and val.present?
    opts[:size] = val.to_sym
  end

  if val=params[:item] and val.present?
    opts[:items] = (opts[:items] || {}).reverse_merge :view=>val.to_sym
  end
end

#main?Boolean

Returns:

  • (Boolean)


136
137
138
# File 'lib/card/format.rb', line 136

def main?
  @depth == 0
end

#nest(nested_card, opts = {}) ⇒ Object



408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
# File 'lib/card/format.rb', line 408

def nest nested_card, opts={}
  #ActiveSupport::Notifications.instrument('wagn', message: "nest: #{nested_card.name}, #{opts}") do
  opts.delete_if { |k,v| v.nil? }
  opts.reverse_merge! inclusion_defaults

  sub = nil
  if opts[:inc_name] =~ /^_(self)?$/
    sub = self
  else
    sub = subformat nested_card
    sub.inclusion_opts = opts[:items] ? opts[:items].clone : {}
  end


  view = canonicalize_view opts.delete :view
  opts[:home_view] = [:closed, :edit].member?(view) ? :open : view
  # FIXME: special views should be represented in view definitions

  view = case
  when @mode == :edit
    if @@perms[view]==:none || nested_card.structure || nested_card.key.blank? # eg {{_self|type}} on new cards
      :blank
    else
      :edit_in_form
    end
  when @mode == :template   ; :template_rule
  when @@perms[view]==:none ; view
  when @mode == :closed     ; !nested_card.known?  ? :closed_missing : :closed_content
  else                      ; view
  end
  sub.render view, opts
  #end
end

#new_inclusion_card_args(options) ⇒ Object



453
454
455
456
457
458
459
460
461
462
463
464
465
# File 'lib/card/format.rb', line 453

def new_inclusion_card_args options
  args = { :name=>options[:inc_name], :type=>options[:type], :supercard=>card }
  args.delete(:supercard) if options[:inc_name].strip.blank? # special case.  gets absolutized incorrectly. fix in smartname?
  if options[:inc_name] =~ /^_main\+/
    # FIXME this is a rather hacky (and untested) way to get @superleft to work on new cards named _main+whatever
    args[:name] = args[:name].gsub /^_main\+/, '+'
    args[:supercard] = root.card
  end
  if content=get_inclusion_content(options[:inc_name])
    args[:content]=content
  end
  args
end

#ok?(task) ⇒ Boolean

Returns:

  • (Boolean)


333
334
335
336
337
338
# File 'lib/card/format.rb', line 333

def ok? task
  task = :create if task == :update && card.new_card?
  @ok ||= {}
  @ok[task] = card.ok? task if @ok[task].nil?
  @ok[task]
end

#ok_view(view, args = {}) ⇒ Object



296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
# File 'lib/card/format.rb', line 296

def ok_view view, args={}
  return view if args.delete :skip_permissions
  approved_view = case
    when @depth >= @@max_depth      ; :too_deep                    # prevent recursion. @depth tracks subformats
    when @@perms[view] == :none     ; view                         # view requires no permissions
    when !card.known? &&
      !tagged( view, :unknown_ok )  ; view_for_unknown view, args  # handle unknown cards (where view not exempt)
    else                            ; permitted_view view, args    # run explicit permission checks
    end

  args[:denied_view] = view if approved_view != view
  if focal? && error_code = @@error_codes[ approved_view ]
    root.error_status = error_code
  end
  approved_view
end

#paramsObject



116
117
118
# File 'lib/card/format.rb', line 116

def params
  Env.params
end

#parse_view_visibility(val) ⇒ Object



223
224
225
# File 'lib/card/format.rb', line 223

def parse_view_visibility val
  (val || '').split( /[\s\,]+/ ).map { |view| canonicalize_view view }
end

#path(opts = {}) ⇒ Object



471
472
473
474
475
476
477
478
479
# File 'lib/card/format.rb', line 471

def path opts={}
  pcard = opts.delete(:card) || card
  base = opts[:action] ? "card/#{ opts.delete :action }/" : ''
  if pcard && !pcard.name.empty? && !opts.delete(:no_id) && ![:new, :create].member?(opts[:action]) #generalize. dislike hardcoding views/actions here
    base += ( opts[:id] ? "~#{ opts.delete :id }" : pcard.cardname.url_key )
  end
  query = opts.empty? ? '' : "?#{opts.to_param}"
  wagn_path( base + query )
end

#permitted_view(view, args) ⇒ Object



317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
# File 'lib/card/format.rb', line 317

def permitted_view view, args
  perms_required = @@perms[view] || :read
  args[:denied_task] =
    if Proc === perms_required
      :read if !(perms_required.call self)  # read isn't quite right
    else
      [perms_required].flatten.find { |task| !ok? task }
    end
  
  if args[:denied_task]
    @@denial_views[view] || :denial
  else
    view
  end
end

#prepare_nest(opts) ⇒ Object



365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
# File 'lib/card/format.rb', line 365

def prepare_nest opts
  @char_count ||= 0
  
  opts ||= {}
  case
  when opts.has_key?( :comment )                            ; opts[:comment]     # as in commented code
  when @mode == :closed && @char_count > @@max_char_count   ; ''                 # already out of view
  when opts[:inc_name]=='_main' && !Env.ajax? && @depth==0  ; expand_main opts
  else
    nested_card = Card.fetch opts[:inc_name], :new=>new_inclusion_card_args(opts)
    result = nest nested_card, opts
    @char_count += result.length if @mode == :closed && result
    result
  end
end

#process_content(content = nil, opts = {}) ⇒ Object



281
282
283
# File 'lib/card/format.rb', line 281

def process_content content=nil, opts={}
  process_content_object(content, opts).to_s
end

#process_content_object(content = nil, opts = {}) ⇒ Object



285
286
287
288
289
290
291
292
293
294
# File 'lib/card/format.rb', line 285

def process_content_object content=nil, opts={}
  return content unless card
  content = card.raw_content || '' if content.nil?

  obj_content = Card::Content===content ? content : Card::Content.new( content, format=self, opts.delete(:content_opts) )
  card.update_references( obj_content, refresh=true ) if card.references_expired  # I thik we need this generalized
  obj_content.process_content_object do |chunk_opts|
    prepare_nest chunk_opts.merge(opts) { yield }
  end
end

#render(view, args = {}) ⇒ Object



181
182
183
184
185
186
187
188
189
190
191
192
193
# File 'lib/card/format.rb', line 181

def render view, args={}
  unless args.delete(:optional) && !show_view?( view, args )
    @current_view = view = ok_view canonicalize_view( view ), args       
    args = default_render_args view, args
    with_inclusion_mode view do
      Wagn.with_logging card.name, :view, view, args do
        send "_view_#{ view }", args
      end
    end
  end
rescue => e
  rescue_view e, view
end

#rendering_error(exception, view) ⇒ Object



264
265
266
# File 'lib/card/format.rb', line 264

def rendering_error exception, view
  "Error rendering: #{error_cardname} (#{view} view)"
end

#rescue_view(e, view) ⇒ Object



245
246
247
248
249
250
251
252
253
254
# File 'lib/card/format.rb', line 245

def rescue_view e, view
  if Rails.env =~ /^cucumber|test$/
    raise e
  else
    Rails.logger.info "\nError rendering #{error_cardname} / #{view}: #{e.class} : #{e.message}"
    Card::Error.current = e
    card.notable_exception_raised
    rendering_error e, view
  end
end

#sessionObject



124
125
126
# File 'lib/card/format.rb', line 124

def session
  Env.session
end

#show_view?(view, args) ⇒ Boolean

Returns:

  • (Boolean)


196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'lib/card/format.rb', line 196

def show_view? view, args
  default = args.delete(:default_visibility) || :show #FIXME - ugly
  view_key = canonicalize_view view
  api_option = args["optional_#{ view_key }".to_sym]
  case 
  # args remove option
  when api_option == :always                   ; true
  when api_option == :never                    ; false
  # wagneer's choice                           
  when show_views( args ).member?( view_key )  ; true
  when hide_views( args ).member?( view_key )  ; false
  # args override default                      
  when api_option == :show                     ; true
  when api_option == :hide                     ; false
  # default                                    
  else                                         ; default==:show
  end
end

#show_views(args) ⇒ Object



215
216
217
# File 'lib/card/format.rb', line 215

def show_views args
  parse_view_visibility args[:show]
end

#showname(title = nil) ⇒ Object



128
129
130
131
132
133
134
# File 'lib/card/format.rb', line 128

def showname title=nil
  if title
    title.to_name.to_absolute_name(card.cardname).to_show *@context_names
  else
    @showname ||= card.cardname.to_show *@context_names
  end
end

#subformat(subcard) ⇒ Object

————- Sub Format and Inclusion Processing ————



272
273
274
275
276
277
278
# File 'lib/card/format.rb', line 272

def subformat subcard
  subcard = Card.fetch( subcard, :new=>{} ) if String===subcard
  sub = self.class.new subcard, :parent=>self, :depth=>@depth+1, :root=>@root,
    # FIXME - the following four should not be hard-coded here.  need a generalized mechanism
    # for attribute inheritance
    :context_names=>@context_names, :mode=>@mode, :mainline=>@mainline, :form=>@form
end

#tagged(view, tag) ⇒ Object



313
314
315
# File 'lib/card/format.rb', line 313

def tagged view, tag
  self.class.tagged view, tag
end

#templateObject



148
149
150
151
152
153
154
155
# File 'lib/card/format.rb', line 148

def template
  @template ||= begin
    c = controller
    t = ActionView::Base.new c.class.view_paths, {:_routes=>c._routes}, c
    t.extend c.class._helpers
    t
  end
end

#unique_idObject



525
526
527
# File 'lib/card/format.rb', line 525

def unique_id
  "#{card.key}-#{Time.now.to_i}-#{rand(3)}" 
end

#unsupported_view(view) ⇒ Object



260
261
262
# File 'lib/card/format.rb', line 260

def unsupported_view view
  "view (#{view}) not supported for #{error_cardname}"
end

#view_for_unknown(view, args) ⇒ Object



340
341
342
343
# File 'lib/card/format.rb', line 340

def view_for_unknown view, args
  # note: overridden in HTML
  focal? ? :not_found : :missing
end

#with_inclusion_mode(mode) ⇒ Object



352
353
354
355
356
357
358
359
360
361
362
363
# File 'lib/card/format.rb', line 352

def with_inclusion_mode mode
  if switch_mode = INCLUSION_MODES[ mode ] and @mode != switch_mode
    old_mode, @mode = @mode, switch_mode
    @inclusion_defaults = nil
  end
  result = yield
  if old_mode
    @inclusion_defaults = nil
    @mode = old_mode
  end
  result
end

#wrap_main(content) ⇒ Object



404
405
406
# File 'lib/card/format.rb', line 404

def wrap_main content
  content  #no wrapping in base format
end