Class: DcPollRenderer

Inherits:
Object
  • Object
show all
Includes:
ActionView::Helpers::FormHelper, ActionView::Helpers::FormOptionsHelper, CmsCommonHelper, DcApplicationHelper
Defined in:
app/renderers/dc_poll_renderer.rb

Overview

Renders code for displaying a poll. Polls may replace forms when user interaction is required in browser.

Instance Attribute Summary

Attributes included from DcApplicationHelper

#design, #form, #ids, #json_ld, #menu, #menu_item, #options, #page, #page_title, #part, #parts, #record, #record_footer, #site, #tables

Instance Method Summary collapse

Methods included from DcApplicationHelper

#_origin, #dc_add2_record_cookie, #dc_add_json_ld, #dc_add_meta_tag, #dc_big_table, #dc_big_table_name_for_value, #dc_choices4, #dc_choices4_all_collections, #dc_choices4_folders_list, #dc_choices4_menu, #dc_choices4_site_policies, #dc_cms_menu, #dc_deprecate, #dc_document_path, #dc_dont?, #dc_edit_mode?, #dc_edit_title, #dc_error_messages_for, #dc_flash_messages, #dc_get_json_ld, #dc_get_link_canonical_tag, #dc_get_seo_meta_tags, #dc_get_site, #dc_icon_for_link, #dc_iframe_edit, #dc_img_alt, #dc_img_alt_tag, #dc_internal_var, #dc_limit_string, #dc_link_for_create, #dc_link_for_edit, #dc_link_for_edit1, #dc_link_menu_tag, #dc_link_to, #dc_menu_class, #dc_new_title, #dc_page_bottom, #dc_page_class, #dc_page_edit_menu, #dc_page_top, #dc_render, #dc_render_design, #dc_render_design_part, #dc_render_from_site, #dc_render_partial, #dc_replace_in_design, #dc_submit_tag, #dc_table_title, #dc_user_can_view, #dc_user_has_role, #dc_warning_messages_for, #decamelize_type

Methods included from CmsCommonHelper

#dc_choices4_field, #dc_choices_for_field, dc_choices_for_field, #dc_date_time, #dc_format_date_time, dc_format_date_time, #dc_format_number, dc_format_number, #dc_help_body, #dc_help_button, #dc_help_fields, #dc_help_for_tab, #dc_icon4_boolean, #dc_icon_for_boolean, #dc_name4_id, #dc_name4_value, #dc_name_for_id, #dc_name_for_value, dc_name_for_value, #dc_steps_menu_get, #t, t, #t_label_for_column, #t_label_for_field, #t_tablename

Constructor Details

#initialize(parent, opts = {}) ⇒ DcPollRenderer

Object initialization.



38
39
40
41
42
43
44
# File 'app/renderers/dc_poll_renderer.rb', line 38

def initialize( parent, opts={} ) #:nodoc:
  @parent   = parent
  @opts     = opts
  @part_css = ''
  @part_js  = ''
  self
end

Instance Method Details

#defaultObject

Default poll renderer method. Renders data for specified pool.



158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
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
249
250
251
252
# File 'app/renderers/dc_poll_renderer.rb', line 158

def default
  # poll_id may be defined in params or opts
  poll_id = @opts[:id] || @opts[:poll_id] || @parent.params[:poll_id]
  return '<br>Poll id is not defined?<br>' if poll_id.nil?

  poll = DcPoll.find(poll_id)
  poll = DcPoll.find_by(name: poll_id) if poll.nil? # name instead of id
  return %(<div class="dc-form-error">Invalid Poll id #{poll_id}</div>) if poll.nil?
  # If parent cant be seen. so cant be polls
  can_view, message = dc_user_can_view(@parent, @parent.page)
  return %(<div class="dc-form-error">#{message}</div>) unless can_view

  html = @opts[:div] ? %(<div id="#{@opts[:div]}"'>) : ''
  html << '<a name="poll-top"></a>'
  unless poll.pre_display.blank?
    begin
      continue, message = eval_pre_display(poll.pre_display)
    rescue Exception => e
      return %(<div class="dc-form-error">Error! Poll pre display. Error: #{e.message}</div>)
    end
    return message unless continue

    html << message if message
  end
  # there might be more than one poll displayed on page. Check if messages and values are for me
  if @parent.flash[:poll_id].nil? || @parent.flash[:poll_id].to_s == poll_id.to_s
    # If flash[:record] is present copy content to params record hash
    @parent.flash[:record].each {|k,v| @parent.params["p_#{k}"] = v } if @parent.flash[:record]  
    # Error during procesing request
    html << %(<div class="dc-form-error">#{@parent.flash[:error]}</div>\n) if @parent.flash[:error].to_s.size > 0
    html << %(<div class="dc-form-info">#{@parent.flash[:info]}</div>\n) if @parent.flash[:info]
  end
  # div and form tag
  html <<  %(<div class="poll-div">\n)
  # edit link
  if @opts[:edit_mode] > 1
    @opts[:editparams].merge!( controller: :cmsedit, action: :edit, id: poll._id, table: :dc_poll, form_name: :dc_poll )
    @opts[:editparams].merge!(title: "#{t('drgcms.edit')}: #{poll.name}")
    @opts[:editparams].delete(:ids) # this is from page, but it gets in a way
    html << dc_link_for_edit( @opts[:editparams] )
  end

  html << case
          when poll.operation == 'poll_submit'
            @parent.form_tag(action: poll.operation, method: :put, return_to: params[:return_to])
          when poll.operation == 'link'
            poll.parameters << "?return_to=#{params[:return_to]}" if params[:return_to]
            @parent.form_tag( poll.parameters, method: :put)
          end
  # header, - on first position will not display title
  html << %(<div class="poll-title">#{poll.title}</div>) unless poll.title[0] == '-'
  html << %(<div class="poll-text">#{poll.sub_text}</div>)
  html << if poll.display == 'lr'
            %(\n<div class="poll-data-table">)
          else
            %(<div class="poll-data-div">\n)
          end
  # items. Convert each item to yaml
  @end_of_data = false
  if poll.form.to_s.size < 10
    items = poll.dc_poll_items
    items.sort! { |a, b| a.order <=> b.order }
    items.each do |item|
      next unless item.active # disabled items
      # convert options to yaml
      yaml = YAML.load(item.options) || {}
      yaml = {} if yaml.class == String
      yaml['name'] = item.name
      yaml['html'] ||= {}
      yaml['html']['size'] = item.size
      (yaml['html']['class'] ||= 'dc-submit') if item.type == 'submit_tag'
      yaml['text'] = item.text
      yaml['mandatory'] = item.mandatory
      yaml['type'] = item.type

      html << do_one_item(poll, yaml)
    end
  else
    yaml = YAML.load(poll.form.gsub('&nbsp;', ' ')) # very annoying. They come with copy&paste ;-)
    # if entered without numbering yaml is returned as Hash otherwise as Array
    yaml.each { |i| html << do_one_item(poll, (i.class == Hash ? i : i.last)) } # 
  end
  # hide some fields usefull as parameters
  html << @parent.hidden_field_tag('return_to', @opts[:return_to] || @parent.params[:return_to])
  html << @parent.hidden_field_tag('return_to_error', @parent.request.url )
  html << @parent.hidden_field_tag('poll_id', poll_id )
  html << @parent.hidden_field_tag('page_id', @parent.page.id )
  # Add javascript code
  html << @parent.javascript_tag(@part_js + poll.js.to_s)
  html << "</form></div>"
  html << '</div>' if @opts[:div]
  
  @part_css = poll.css
  html
end

#do_one_item(poll, yaml) ⇒ Object

Outputs code required for poll item. Subroutine of default method.



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
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
# File 'app/renderers/dc_poll_renderer.rb', line 56

def do_one_item(poll, yaml)
  html = ''
  yaml['separator'] ||= ''
  yaml['text']      ||= ''
  # label
  text = yaml['text'].match(/\./) ? t(yaml['text']) : yaml['text'] 
  if yaml['mandatory']
    text << ( poll.display == 'in' ? ' *' : '<span class="required"> *</span>' )
    yaml['html'] ||= {}
    yaml['html']['required'] = true
  else
    text << " &nbsp;" if poll.display == 'lr' and !yaml['type'].match(/submit_tag|link_to/)
  end
  
  # Just add text if comment and go to next one
  if yaml['type'] == 'comment'
    html << if poll.display == 'lr'
      "<div class='row-div'><div class='dc-form-label poll-data-text comment'>#{text}</div></div>"
    else
      "<div class='poll-data-text comment'>#{text}</div>"
    end    
    return html
  end

  # Set default value, if not already set
  if yaml['default'] 
    if yaml['default'].match('eval')
      e = yaml['default'].match(/\((.*?)\)/)[1]
      yaml['default'] = eval e
    elsif yaml['default'].match('params')
      param_name = yaml['default'].split(/\.|\ |\,/)[1]
      yaml['default'] = @parent.params[param_name]
    end
    key = "p_#{yaml['name']}"
    params[key] = yaml['default'] unless params[key]
  end
  # Label as placeholder
  if poll.display == 'in'
    yaml['html'] ||= {}
    yaml['html']['placeholder'] = text
  end
  # create form_field object and retrieve html code
  clas_string = yaml['type'].camelize
  field_html = if DrgcmsFormFields.const_defined?(clas_string) 
    clas = DrgcmsFormFields.const_get(clas_string)
    field = clas.new(@parent, @record, yaml).render
    @part_js << field.js
    field.html
  else # error string
    "Error: Code for field type #{yaml['type']} not defined!"
  end

  if yaml['type'].match(/submit_tag|link_to/)
    # There can be more than one links on form. End the data at first link or submit.
    if !@end_of_data 
      html << (poll.display == 'lr' ? "</div><br>\n" : "</div>\n")
      # captcha
      if poll.captcha_type.present?
        @opts.merge!(:captcha_type => poll.captcha_type)
        captcha = DcCaptchaRenderer.new(@parent, @opts)
        html << captcha.render_html
        @part_css = captcha.render_css
      end
      @end_of_data = true
    end
    # submit and link tag
    clas = yaml['type'].match(/submit_tag/) ? '' : 'dc-link-submit'
    html << "<span class='#{clas}'>#{field_html}#{yaml['separator']}</span>"
  # other fields
  else
    html << case
      when poll.display == 'lr' then
      "<div class='row-div'><div class='dc-form-label poll-data-text lr #{yaml['class']}'>#{text}</div><div class='poll-data-field td #{yaml['class']}'>#{field_html}</div></div>\n"
      when poll.display == 'td' then
      "<div class='poll-data-text td #{yaml['class']}'>#{text}</div><div class='poll-data-field td #{yaml['class']}'>#{field_html}#{yaml['separator']}</div>\n"
      else
      "<div class='poll-data-field in #{yaml['class']}'>#{field_html}#{yaml['separator']}</div>\n"
    end    
  end
end

#eval_pre_display(code) ⇒ Object

Call method before poll is displayed. Usefull for filling predefined values into flash[value] Method cane be defined as ClassName.method or only method. If only method is defined then method name must exist in helpers.

Called method must return at least one result if process can continue.



144
145
146
147
148
149
150
151
152
153
# File 'app/renderers/dc_poll_renderer.rb', line 144

def eval_pre_display(code)
  a = code.strip.split('.')
  if a.size == 1
    continue, message = @parent.send(a.first)
  else
    klass = a.first.classify.constantize
    continue, message = klass.send(a.last,@parent)
  end
  [continue, message]
end

#paramsObject

Dummy params method for accesing session params object from form.



49
50
51
# File 'app/renderers/dc_poll_renderer.rb', line 49

def params
  @parent.params
end

#render_cssObject

Return CSS part of code.



265
266
267
# File 'app/renderers/dc_poll_renderer.rb', line 265

def render_css
  @part_css
end

#render_htmlObject

Renderer dispatcher. Method returns HTML part of code.



257
258
259
260
# File 'app/renderers/dc_poll_renderer.rb', line 257

def render_html
  method = @opts[:method] || 'default'
  respond_to?(method) ? send(method) : "Error DcPoll: Method #{method} doesn't exist!"
end