Sha256: 22c394220682c4c39ca00fc66a672c4acd4b02c3ba64ef90c3272e76375ca00a

Contents?: true

Size: 1.03 KB

Versions: 8

Compression:

Stored size: 1.03 KB

Contents

module Helena
  class Answer
    include Helena::Concerns::ApplicationModel

    field :code,        type: String
    field :ip_address,  type: String
    field :created_at,  type: DateTime, default: -> { DateTime.now }

    embedded_in :session, inverse_of: :answers

    validates :code, presence: true, uniqueness: true

    def self.build_generic(code, value, ip_address)
      value = cast_value(value)
      answer_class_for(value).new(code: code, value: value, ip_address: ip_address)
    end

    def self.answer_class_for(value)
      case value
      when Fixnum
        Helena::IntegerAnswer
      when TrueClass
        Helena::BooleanAnswer
      when FalseClass
        Helena::BooleanAnswer
      when String
        Helena::StringAnswer
      end
    end

    def self.cast_value(value)
      if value == 'true'
        true
      elsif value == 'false'
        false
      elsif integer?(value)
        value.to_i
      else
        value.to_s
      end
    end

    def self.integer?(str)
      Integer(str) rescue false
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
helena-1.1.0 app/models/helena/answer.rb
helena-1.0.3 app/models/helena/answer.rb
helena-1.0.2 app/models/helena/answer.rb
helena-1.0.1 app/models/helena/answer.rb
helena-1.0.0.rc4 app/models/helena/answer.rb
helena-1.0.0.rc3 app/models/helena/answer.rb
helena-1.0.0.rc2 app/models/helena/answer.rb
helena-1.0.0.rc1 app/models/helena/answer.rb