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
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/api_resource/typecast.rb', line 65 def default_typecasters @default_typecasters ||= { :boolean => BooleanTypecaster, :bool => BooleanTypecaster, :date => DateTypecaster, :decimal => FloatTypecaster, :float => FloatTypecaster, :integer => IntegerTypecaster, :int => IntegerTypecaster, :string => StringTypecaster, :text => StringTypecaster, :time => TimeTypecaster, :datetime => TimeTypecaster, :array => ArrayTypecaster, } 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
56 57 58 59 60 61 62 63 |
# File 'lib/api_resource/typecast.rb', line 56 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)
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/api_resource/typecast.rb', line 29 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 |