Module: Wrest::Components::Container::Typecaster

Defined in:
lib/wrest/components/container/typecaster.rb

Overview

An extension to Container that adds support for specifying how the values associated with certain attribute keys should be typecast.

This extension can be used in situations where the attributes hash consists of just strings with no associated tup information. For example, params recieved from a web browser may contain attributes like

'id' => '4', 'dateofbirth' => '1984-04-05'

and we’d like to have these cast to an integer and a date respectively, rather than have to deal with them as strings.

Defined Under Namespace

Modules: ClassMethods, Helpers, InstanceMethods

Constant Summary collapse

PARSING =
{
  'symbol' => proc { |symbol| symbol.to_s.to_sym },
  'date' => proc { |date| ::Date.parse(date) },
  'datetime' => proc { |time|
    begin
      Time.xmlschema(time).utc
    rescue StandardError
      ::DateTime.parse(time).utc
    end
  },
  'integer' => proc { |integer| integer.to_i },
  'float' => proc { |float| float.to_f },
  'decimal' => proc do |number|
    if number.is_a?(String)
      number.to_d
    else
      BigDecimal(number)
    end
  end,
  'boolean' => proc { |boolean| %w[1 true].include?(boolean.to_s.strip) },
  'string' => proc { |string| string.to_s },
  'yaml' => proc { |yaml|
    begin
      YAML.safe_load(yaml)
    rescue StandardError
      yaml
    end
  },
  'base64Binary' => proc { |bin| ::Base64.decode64(bin) },
  'binary' => proc { |bin, entity| _parse_binary(bin, entity) },
  'file' => proc { |file, entity| _parse_file(file, entity) },
  'double' => proc { |float| float.to_f },
  'dateTime' => proc { |time|
    begin
      Time.xmlschema(time).utc
    rescue StandardError
      ::DateTime.parse(time).utc
    end
  }
}.freeze

Class Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



68
69
70
71
72
73
74
# File 'lib/wrest/components/container/typecaster.rb', line 68

def self.included(klass)
  # :nodoc:
  klass.extend Typecaster::ClassMethods
  klass.class_eval { include Typecaster::InstanceMethods }
  klass.send(:alias_method, :initialize_without_typecasting, :initialize)
  klass.send(:alias_method, :initialize, :initialize_with_typecasting)
end