Class: Quby::Questionnaires::Entities::Questionnaire

Inherits:
Object
  • Object
show all
Extended by:
ActiveModel::Naming
Includes:
ActiveModel::Validations
Defined in:
lib/quby/questionnaires/entities/questionnaire.rb

Defined Under Namespace

Classes: InputKeyAlreadyDefined, UnknownInputKey, ValidationError

Constant Summary collapse

VALID_LICENSES =
[:unknown,
:free,               # freely available without license costs,
:pay_per_completion, # costs associated with each completed questionnaire,
:private,            # not a publicly available questionnaire
:deprecated]
RESPONDENT_TYPES =
%i( profess patient parent second_parent teacher caregiver )

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key, last_update: Time.now) ⇒ Questionnaire

Returns a new instance of Questionnaire.



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 32

def initialize(key, last_update: Time.now)
  @key = key
  @sbg_domains = []
  @last_update = Time.at(last_update.to_i)
  @score_calculations = {}.with_indifferent_access
  @charts = Charting::Charts.new
  @fields = Fields.new(self)
  @license = :unknown
  @renderer_version = :v1
  @extra_css = ""
  @allow_switch_to_bulk = false
  @panels = []
  @flags = {}.with_indifferent_access
  @textvars = {}.with_indifferent_access
  @language = :nl
  @respondent_types = []
  @tags = OpenStruct.new
  @check_key_clashes = true
  @validate_html = true
  @score_schemas = {}.with_indifferent_access
  @outcome_tables = []
  @check_score_keys_consistency = true
end

Instance Attribute Details

#abortableObject

Returns the value of attribute abortable.



64
65
66
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 64

def abortable
  @abortable
end

#allow_hotkeysObject

allow hotkeys for :all views, just :bulk views (default), or :none for never



89
90
91
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 89

def allow_hotkeys
  @allow_hotkeys
end

#allow_switch_to_bulkObject

Returns the value of attribute allow_switch_to_bulk.



73
74
75
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 73

def allow_switch_to_bulk
  @allow_switch_to_bulk
end

#chartsObject

Returns the value of attribute charts.



92
93
94
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 92

def charts
  @charts
end

#check_key_clashesObject

whether to check for clashes between question input keys (HTML form keys)



82
83
84
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 82

def check_key_clashes
  @check_key_clashes
end

#check_score_keys_consistencyObject

whether to check consistency of score subkeys during seed generation



84
85
86
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 84

def check_score_keys_consistency
  @check_score_keys_consistency
end

#deactivate_answers_requested_atObject

Returns the value of attribute deactivate_answers_requested_at.



80
81
82
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 80

def deactivate_answers_requested_at
  @deactivate_answers_requested_at
end

#default_answer_valueObject

Returns the value of attribute default_answer_value.



68
69
70
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 68

def default_answer_value
  @default_answer_value
end

#descriptionObject

Returns the value of attribute description.



58
59
60
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 58

def description
  @description
end

#enable_previous_questionnaire_buttonObject

Returns the value of attribute enable_previous_questionnaire_button.



65
66
67
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 65

def enable_previous_questionnaire_button
  @enable_previous_questionnaire_button
end

#extra_cssObject

Returns the value of attribute extra_css.



72
73
74
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 72

def extra_css
  @extra_css
end

#fieldsObject (readonly)

Returns the value of attribute fields.



71
72
73
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 71

def fields
  @fields
end

#flagsObject

Returns the value of attribute flags.



94
95
96
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 94

def flags
  @flags
end

#keyObject

Returns the value of attribute key.



56
57
58
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 56

def key
  @key
end

#languageObject

Returns the value of attribute language.



76
77
78
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 76

def language
  @language
end

#last_authorObject

Returns the value of attribute last_author.



88
89
90
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 88

def last_author
  @last_author
end

#last_updateObject

Returns the value of attribute last_update.



90
91
92
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 90

def last_update
  @last_update
end

#leave_page_alertObject

Returns the value of attribute leave_page_alert.



70
71
72
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 70

def leave_page_alert
  @leave_page_alert
end

#licenseObject

Returns the value of attribute license.



74
75
76
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 74

def license
  @license
end

#licensorObject

Returns the value of attribute licensor.



75
76
77
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 75

def licensor
  @licensor
end

#outcome_descriptionObject

Returns the value of attribute outcome_description.



59
60
61
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 59

def outcome_description
  @outcome_description
end

#outcome_regeneration_requested_atObject

Returns the value of attribute outcome_regeneration_requested_at.



79
80
81
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 79

def outcome_regeneration_requested_at
  @outcome_regeneration_requested_at
end

#outcome_tablesObject

Returns the value of attribute outcome_tables.



97
98
99
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 97

def outcome_tables
  @outcome_tables
end

#panelsObject

Returns the value of attribute panels.



66
67
68
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 66

def panels
  @panels
end

#renderer_versionObject

Returns the value of attribute renderer_version.



69
70
71
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 69

def renderer_version
  @renderer_version
end

#respondent_typesObject

Returns the value of attribute respondent_types.



77
78
79
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 77

def respondent_types
  @respondent_types
end

#roqua_keysObject

Returns the value of attribute roqua_keys.



61
62
63
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 61

def roqua_keys
  @roqua_keys
end

#sbg_domainsObject

Returns the value of attribute sbg_domains.



63
64
65
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 63

def sbg_domains
  @sbg_domains
end

#sbg_keyObject

not required to be unique



62
63
64
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 62

def sbg_key
  @sbg_key
end

#score_calculationsObject

Returns the value of attribute score_calculations.



67
68
69
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 67

def score_calculations
  @score_calculations
end

#score_schemasObject

Returns the value of attribute score_schemas.



98
99
100
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 98

def score_schemas
  @score_schemas
end

#short_descriptionObject

Returns the value of attribute short_description.



60
61
62
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 60

def short_description
  @short_description
end

#tagsObject

tags= is manually defined below



78
79
80
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 78

def tags
  @tags
end

#textvarsObject

Returns the value of attribute textvars.



95
96
97
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 95

def textvars
  @textvars
end

#titleObject

Returns the value of attribute title.



57
58
59
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 57

def title
  @title
end

#validate_htmlObject

If false, we don’t check html for validity (for mate1 and mate1_pre)



86
87
88
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 86

def validate_html
  @validate_html
end

Instance Method Details

#actionsObject



265
266
267
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 265

def actions
  score_calculations.values.select(&:action)
end

#add_chart(chart) ⇒ Object



273
274
275
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 273

def add_chart(chart)
  charts.add chart
end

#add_flag(flag_options) ⇒ Object



277
278
279
280
281
282
283
284
285
286
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 277

def add_flag(flag_options)
  if flag_options[:internal]
    flag_key = flag_options[:key].to_sym
  else
    flag_key = "#{key}_#{flag_options[:key]}".to_sym
  end
  flag_options[:key] = flag_key
  fail(ArgumentError, "Flag '#{flag_key}' already defined") if flags.key?(flag_key)
  flags[flag_key] = Flag.new(flag_options)
end

#add_outcome_table(outcome_table_options) ⇒ Object



402
403
404
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 402

def add_outcome_table(outcome_table_options)
  outcome_tables << OutcomeTable.new(**outcome_table_options, questionnaire: self)
end

#add_panel(panel) ⇒ Object



125
126
127
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 125

def add_panel(panel)
  @panels << panel
end

#add_score_calculation(builder) ⇒ Object



241
242
243
244
245
246
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 241

def add_score_calculation(builder)
  if score_calculations.key?(builder.key)
    fail InputKeyAlreadyDefined, "Score key `#{builder.key}` already defined."
  end
  score_calculations[builder.key] = builder
end

#add_score_schema(key, label, sub_schema_options) ⇒ Object



248
249
250
251
252
253
254
255
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 248

def add_score_schema(key, label, sub_schema_options)
  schema = Entities::ScoreSchema.new(key: key, label: label, sub_score_schemas: sub_schema_options)
  schema.valid?
  schema.errors.each do |attribute, message|
    errors.add("Score schema '#{key}'", "#{attribute} #{message}")
  end
  score_schemas[key] = schema
end

#add_textvar(textvar_options) ⇒ Object



294
295
296
297
298
299
300
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 294

def add_textvar(textvar_options)
  textvar_key = "#{key}_#{textvar_options.fetch(:key)}".to_sym
  textvar_options[:key] = textvar_key
  validate_textvar_keys_unique(textvar_key)
  validate_depends_on_flag(textvar_key, textvar_options)
  textvars[textvar_key] = Textvar.new(textvar_options)
end

#answer_dsl_moduleObject

rubocop:disable Metrics/MethodLength



314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 314

def answer_dsl_module # rubocop:disable Metrics/MethodLength
  # Have to put this in a local variable so the module definition block can access it
  questions_in_var = questions

  @answer_dsl_cache ||= Module.new do
    questions_in_var.each do |question|
      next if question&.key.blank?
      case question.type
      when :date
        question.components.each do |component|
          # assignment to 'value' hash must be done under string keys
          key = question.send("#{component}_key").to_s
          define_method(key) do
            self.value ||= Hash.new
            self.value[key]
          end

          define_method("#{key}=") do |v|
            self.value ||= Hash.new
            self.value[key] = v&.strip
          end
        end

        define_method(question.key) do
          self.value ||= Hash.new

          components = question.components.sort
          component_values = components.map do |component|
            value_key = question.send("#{component}_key").to_s
            self.value[value_key]
          end
          case components
          when [:day, :month, :year]
            component_values.reverse.take_while { |p| p.present? }.reverse.join('-')
          when [:month, :year]
            component_values.reject(&:blank?).join('-')
          when [:hour, :minute]
            component_values.all?(&:blank?) ? '' : component_values.join(':')
          end
        end

      when :check_box

        define_method(question.key) do
          self.value ||= Hash.new
          self.value[question.key.to_s] ||= Hash.new
        end

        question.options.each do |opt|
          next if opt&.key.blank?
          define_method("#{opt.key}") do
            self.value ||= Hash.new
            self.value[question.key.to_s] ||= Hash.new
            self.value[opt.key.to_s] ||= 0
          end

          define_method("#{opt.key}=") do |v|
            v = v.to_i
            self.value ||= Hash.new
            self.value[question.key.to_s] ||= Hash.new
            self.value[question.key.to_s][opt.key.to_s] = v
            self.value[opt.key.to_s] = v
          end
        end
      else
        # Includes:
        # question.type == :radio
        # question.type == :scale
        # question.type == :select
        # question.type == :string
        # question.type == :textarea
        # question.type == :integer
        # question.type == :float

        define_method(question.key) do
          self.value ||= Hash.new
          self.value[question.key.to_s]
        end

        define_method(question.key.to_s + "=") do |v|
          self.value ||= Hash.new
          self.value[question.key.to_s] = v
        end
      end rescue nil
    end
  end
end

#as_json(options = {}) ⇒ Object



184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 184

def as_json(options = {})
  {
    key: key,
    title: title,
    description: description,
    outcomeDescription: outcome_description,
    shortDescription: short_description,
    panels: panels,
    fields: fields,
    flags: flags,
    textvars: textvars,
    validations: validations,
    visibilityRules: visibility_rules
  }
end

#callback_after_dsl_enhance_on_questionsObject



137
138
139
140
141
142
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 137

def callback_after_dsl_enhance_on_questions
  question_hash.each_value do |q|
    q.run_callbacks :after_dsl_enhance
  end
  ensure_scores_have_schemas if Quby::Settings.require_score_schemas
end

#completionObject



269
270
271
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 269

def completion
  score_calculations.values.select(&:completion).first
end

#default_textvarsObject



308
309
310
311
312
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 308

def default_textvars
  textvars.select { |key, textvar| textvar.default.present? }
          .map    { |key, textvar| [key, textvar.default] }
          .to_h
end

#ensure_scores_have_schemasObject



144
145
146
147
148
149
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 144

def ensure_scores_have_schemas
  missing_schemas = scores.map(&:key).map(&:to_s) - score_schemas.keys
  missing_schemas.each do |key|
    errors.add "Score #{key}", 'is missing a score schema'
  end
end

#filter_flags(given_flags) ⇒ Object



288
289
290
291
292
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 288

def filter_flags(given_flags)
  given_flags.select do |flag_key, _|
    flags.key? flag_key
  end
end

#filter_textvars(given_textvars) ⇒ Object



302
303
304
305
306
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 302

def filter_textvars(given_textvars)
  given_textvars.select do |textvar_key, _|
    textvars.key? textvar_key
  end
end

#find_plottable(key) ⇒ Object



261
262
263
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 261

def find_plottable(key)
  score_calculations[key] || question_hash.with_indifferent_access[key]
end

#key_in_use?(key) ⇒ Boolean

rubocop:enable Metrics/MethodLength

Returns:

  • (Boolean)


237
238
239
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 237

def key_in_use?(key)
  fields.key_in_use?(key) || score_calculations.key?(key)
end

#questionsObject



171
172
173
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 171

def questions
  question_hash.values
end

#questions_of_type(type) ⇒ Object



175
176
177
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 175

def questions_of_type(type)
  questions.select { |question| question.type == type }
end

#questions_treeObject



159
160
161
162
163
164
165
166
167
168
169
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 159

def questions_tree
  return @questions_tree_cache if @questions_tree_cache

  recurse = lambda do |question|
    [question, question.subquestions.map(&recurse)]
  end

  @questions_tree_cache = (@panels && @panels.map do |panel|
    panel.items.map { |item| recurse.call(item) if item.is_a?(Quby::Questionnaires::Entities::Question) }
  end)
end

#register_question(question) ⇒ Object



129
130
131
132
133
134
135
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 129

def register_question(question)
  fields.add(question)

  if question.sets_textvar && !textvars.key?(question.sets_textvar)
    fail "Undefined textvar: #{question.sets_textvar}"
  end
end

#scoresObject



257
258
259
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 257

def scores
  score_calculations.values.select(&:score)
end

#to_codebook(options = {}) ⇒ Object

rubocop:disable Metrics/MethodLength



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/quby/questionnaires/entities/questionnaire.rb', line 201

def to_codebook(options = {})
  output = []
  output << title
  output << "Date unknown"
  output << ""

  options[:extra_vars]&.each do |var|
    output << "#{var[:key]} #{var[:type]}"
    output << "\"#{var[:description]}\""
    output << ""
  end

  top_questions = panels.map do |panel|
    panel.items.select { |item| item.is_a? Question }
  end.flatten.compact

  top_questions.each do |question|
    output << question.to_codebook(self, options)
    output << ""
  end

  flags.each_value do |flag|
    output << flag.to_codebook(options)
    output << ""
  end

  textvars.each_value do |textvar|
    output << textvar.to_codebook(options)
    output << ""
  end

  output = output.join("\n")
  strip_tags(output.gsub(/\<([ 1-9])/, '&lt;\1')).gsub("&lt;", "<")
end

#to_paramObject



121
122
123
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 121

def to_param
  key
end

#validate_questionsObject



151
152
153
154
155
156
157
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 151

def validate_questions
  question_hash.each_value do |q|
    unless q.valid?
      q.errors.each { |attr, err| errors.add(attr, err) }
    end
  end
end

#validationsObject



406
407
408
409
410
411
412
413
414
415
416
417
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 406

def validations
  @validations ||= fields.question_hash.values.flat_map do |question|
    question.validations.map do |validation|
      case validation[:type]
      when :answer_group_minimum, :answer_group_maximum
        Validation.new(validation.merge(field_keys: questions.select {|q| q.question_group == validation[:group]}.map(&:key)))
      else
        Validation.new(validation.merge(field_key: question.key))
      end
    end
  end.uniq(&:config)
end

#visibility_rulesObject



419
420
421
422
# File 'lib/quby/questionnaires/entities/questionnaire.rb', line 419

def visibility_rules
  @visibility_rules ||= fields.question_hash.values.flat_map { |question| VisibilityRule.from(question) } \
                      + flags.values.flat_map { |flag| VisibilityRule.from_flag(flag) }
end