require 'time'

##
# NPR::Concern::AttrTypecast
#
module NPR
  #------------------
  # Attributes that are being typecast to Ruby classes
  ATTR_TYPES = {
    "id"               => Fixnum,
    "partnerId"        => Fixnum,
    "storyDate"        => Time, 
    "pubDate"          => Time,
    "lastModifiedDate" => Time,
    "showDate"         => Time,
    "date"             => Time,
    "segNum"           => Fixnum,
    "num"              => Fixnum
  }
  
  #------------------
  # How to typecast
  CASTERS = {
    Fixnum => lambda { |a| a.to_i },
    Time   => lambda { |a| !a.empty? ? Time.parse(a) : nil }
  }
  
  module Concern
    module AttrTypecast
      
      private
      
      #------------------
      
      def attr_typecast(key, value)
        if type = NPR::ATTR_TYPES[key]
          typecast(value, type)
        else
          value
        end
      end

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

      def typecast(value, klass)
        NPR::CASTERS[klass].call(value)
      end      
    end # AttrTypecast
  end # Concern
end # NPR

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
  }
  
  module Concern
    module AttrTypecast
      
      private
      
      #------------------
      # Typecasting methods
      def string_to_i(value)
        value.to_i
      end
      
      #------------------
      
      def string_time_parse(value)
        !value.empty? ? Time.parse(value) : nil
      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

Refactor Typecasting to use custom methods
Refactor Typecasting to use custom methods
