Sha256: a76d7dc6d767e4e16470439d55186e0ff59b258b1c634c1f1fee09773e426713

Contents?: true

Size: 1.97 KB

Versions: 1

Compression:

Stored size: 1.97 KB

Contents

# Copyright: Copyright 2010 Topic Maps Lab, University of Leipzig.
# License:   Apache License, Version 2.0

module Sugar::Occurrence
  module DynamicValue
    # Returns the value of this occurrence cast as appropriate Ruby type.
    def dynamic_value
      case self.datatype.to_external_form # first_oc.datatype is actually of type Locator
        when RTM::PSI[:Decimal]
          self.value.to_f
        when RTM::PSI[:Double]
          self.value.to_f
        when RTM::PSI[:Int]
          self.value.to_i
        when RTM::PSI[:Integer]
          self.value.to_i
        when RTM::PSI[:Float]
          self.value.to_f
        when RTM::PSI[:Long]
          self.value.to_i
        # Date, ... missing
        else
          self.value
      end
    end
    
    class NoDatatypeHandlerAvailableException < Exception
      def initialize(value)
        super "Cannot map #{value} to an occurrence value+datatype. Maybe you need to add a handler for your Ruby object type."
      end
    end
  end
end

class Float
  def to_xsd_double
    s = self.to_s
    
    case s
      when "Infinity"
        "INF"
      when "-Infinity"
        "-INF"
      else
        s
    end
  end
end

module Sugar::Topic::Characteristics
  #
  # Weird. create_occurrence has an options hash, and we don't have one. We should unify the syntax. What is the right thing to do?
  #
  def dynamic_create_occurrence(type,value,datatype,scope = nil)
    if !datatype # well, let's choose one
      case value
        when Integer
          datatype = RTM::PSI[:Integer]
          use_value = value.to_s
        when Float
          datatype = RTM::PSI[:Double]
          use_value = value.to_xsd_double
        when String
          datatype = RTM::PSI[:String]
          use_value = value
        else
          raise Sugar::Occurrence::DynamicValue::NoDatatypeHandlerAvailableException.new(value)
      end
    else
      use_value = value
    end
    
    create_occurrence(type,use_value,:datatype => datatype, :scope => scope)
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
rtm-0.2.0 lib/rtm/sugar/occurrence/dynamic_value.rb