Module: ApiResource::Typecast::ClassMethods
- Defined in:
- lib/api_resource/typecast.rb
Instance Method Summary collapse
- #default_typecasters ⇒ Object
-
#redefine_typecaster!(name, klass = nil, &block) ⇒ Object
Redefines a typecaster (or defines it if it doesn’t exist) basically just delegates to register_typecaster.
-
#register_typecaster(name, klass = nil, &block) ⇒ Object
Takes a typecaster name (converted to all lowercase) and either a klass (as a constant) or a block to define an anonymous module and registers a new typecaster that defines the method typecast!(value).
Instance Method Details
#default_typecasters ⇒ Object
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 |
# File 'lib/api_resource/typecast.rb', line 75 def default_typecasters @default_typecasters ||= { :array => ArrayTypecaster, :boolean => BooleanTypecaster, :bool => BooleanTypecaster, :date => DateTypecaster, :datetime => TimeTypecaster, :decimal => FloatTypecaster, :float => FloatTypecaster, :integer => IntegerTypecaster, :int => IntegerTypecaster, :string => StringTypecaster, :text => StringTypecaster, :time => TimeTypecaster, :unknown => UnknownTypecaster } end |
#redefine_typecaster!(name, klass = nil, &block) ⇒ Object
Redefines a typecaster (or defines it if it doesn’t exist) basically just delegates to register_typecaster
66 67 68 69 70 71 72 73 |
# File 'lib/api_resource/typecast.rb', line 66 def redefine_typecaster!(name, klass = nil, &block) caster = name.to_s.downcase.to_sym # clone the original typecasters hash so that the override # only applies to this class and subclasses self.typecasters = self.typecasters.clone self.typecasters.delete(caster) self.register_typecaster(name, klass, &block) end |
#register_typecaster(name, klass = nil, &block) ⇒ Object
Takes a typecaster name (converted to all lowercase) and either a klass (as a constant) or a block to define an anonymous module and registers a new typecaster that defines the method typecast!(value)
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/api_resource/typecast.rb', line 39 def register_typecaster(name, klass = nil, &block) caster = name.to_s.downcase.to_sym if self.typecasters[caster] raise ArgumentError, "Typecaster #{name} already exists" end if block_given? unless klass.nil? raise ArgumentError, "Cannot declare a typecaster with a class and a block" end klass = Module.new(&block) elsif klass.nil? raise ArgumentError, "Must specify a typecaster with either a class or a block" end unless klass.respond_to?(:from_api) && klass.respond_to?(:to_api) raise ArgumentError, "Typecaster must respond to from_api and to_api" end self.typecasters[caster] = klass end |