Class: Interrogative::Question

Inherits:
Object
  • Object
show all
Defined in:
lib/interrogative/question.rb

Overview

A question with a unique name and a textual representation.

Designed to translate well into an HTML form element without betraying the fact that it's meant to transform into an HTML form element.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, text, owner = nil, attrs = {}) ⇒ Question

Returns a new instance of Question.

See Also:

  • Interrogative#question


15
16
17
18
19
20
# File 'lib/interrogative/question.rb', line 15

def initialize(name, text, owner=nil, attrs={})
  @name = name or raise ArgumentError, "A question must have a name."
  @text = text or raise ArgumentError, "A question must have a label."
  @owner = owner
  @attrs = attrs
end

Instance Attribute Details

#attrsObject

Returns the value of attribute attrs.



12
13
14
# File 'lib/interrogative/question.rb', line 12

def attrs
  @attrs
end

#nameObject

Returns the value of attribute name.



12
13
14
# File 'lib/interrogative/question.rb', line 12

def name
  @name
end

#textObject

Returns the value of attribute text.



12
13
14
# File 'lib/interrogative/question.rb', line 12

def text
  @text
end

Instance Method Details

#optionsArray, Hash

Possible answers for the question.

Returns nil unless the class that included Interrogative responds to a method called #{ name }_options; otherwise, it returns the result of calling that method.

Options should be either an Array or a Hash. In the case of a Hash, the format should be { text => value }.

Returns:

  • (Array, Hash)

    the possible answers for the question.



32
33
34
35
36
37
38
39
# File 'lib/interrogative/question.rb', line 32

def options
  return nil if @owner.nil?

  options_method = "#{@name}_options".intern
  if @owner.respond_to? options_method
    @owner.send options_method
  end
end

#to_hashHash

Returns a hash representation of the question.

Attributes are merged into the top level, along with :text and :name. Possible options are nested under :options.

Returns:

  • (Hash)


47
48
49
50
51
52
53
54
55
56
# File 'lib/interrogative/question.rb', line 47

def to_hash
  h = @attrs.merge({
    :text => text,
    :name => name,
  })

  o = options
  h[:options] = o if not o.nil?
  return h
end

#to_json(opts = {}) ⇒ String

Returns a JSON object created from the question's hash representation.

Returns:

  • (String)

See Also:



63
64
65
# File 'lib/interrogative/question.rb', line 63

def to_json(opts={})
  self.to_hash.to_json(opts)
end