Sha256: cde994a851a1ee6163d04caf75f9bdc206e9898d2935662a62ca397d8210fe2f

Contents?: true

Size: 1.29 KB

Versions: 1

Compression:

Stored size: 1.29 KB

Contents

require 'time'

##
# NPR::Concern::AttrTypecast
#
module NPR
  #------------------
  # Attributes that are being typecast to Ruby classes
  ATTR_TYPES = {
    "id"               => :string_to_i,
    "partnerId"        => :string_to_i,
    "storyDate"        => :string_time_parse,
    "pubDate"          => :string_time_parse,
    "lastModifiedDate" => :string_time_parse,
    "showDate"         => :string_time_parse,
    "date"             => :string_time_parse,
    "segNum"           => :string_to_i,
    "num"              => :string_to_i,
    "timestamp"        => :string_time_at,
    "duration"         => :string_to_i
  }

  module Concern
    module AttrTypecast

      private

      #------------------
      # Typecasting methods
      def string_to_i(value)
        value.to_i
      end

      #------------------

      def string_time_parse(value)
        begin
          !value.empty? ? Time.parse(value) : nil
        rescue ArgumentError
          nil
        end
      end

      #------------------

      def string_time_at(value)
        Time.at(value.to_f)
      end

      #------------------

      def attr_typecast(key, value)
        if method = NPR::ATTR_TYPES[key]
          send method, value
        else
          value
        end
      end
    end # AttrTypecast
  end # Concern
end # NPR

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
npr-3.0.0 lib/npr/concern/attr_typecast.rb