Class: Interrogative::Question
- Inherits:
-
Object
- Object
- Interrogative::Question
- 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
-
#attrs ⇒ Object
Returns the value of attribute attrs.
-
#name ⇒ Object
Returns the value of attribute name.
-
#text ⇒ Object
Returns the value of attribute text.
Instance Method Summary collapse
-
#initialize(name, text, owner = nil, attrs = {}) ⇒ Question
constructor
A new instance of Question.
-
#options ⇒ Array, Hash
Possible answers for the question.
-
#to_hash ⇒ Hash
Returns a hash representation of the question.
-
#to_json(opts = {}) ⇒ String
Returns a JSON object created from the question's hash representation.
Constructor Details
#initialize(name, text, owner = nil, attrs = {}) ⇒ Question
Returns a new instance of 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
#attrs ⇒ Object
Returns the value of attribute attrs.
12 13 14 |
# File 'lib/interrogative/question.rb', line 12 def attrs @attrs end |
#name ⇒ Object
Returns the value of attribute name.
12 13 14 |
# File 'lib/interrogative/question.rb', line 12 def name @name end |
#text ⇒ Object
Returns the value of attribute text.
12 13 14 |
# File 'lib/interrogative/question.rb', line 12 def text @text end |
Instance Method Details
#options ⇒ Array, 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 }.
32 33 34 35 36 37 38 39 |
# File 'lib/interrogative/question.rb', line 32 def return nil if @owner.nil? = "#{@name}_options".intern if @owner.respond_to? @owner.send end end |
#to_hash ⇒ Hash
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.
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 = 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.
63 64 65 |
# File 'lib/interrogative/question.rb', line 63 def to_json(opts={}) self.to_hash.to_json(opts) end |