@@ -93,6 +93,24 @@ def self.exposures
9393 @exposures
9494 end
9595
96+ # This allows you to declare a Proc in which exposures can be formatted with.
97+ # It take a block with an arity of 1 which is passed as the value of the exposed attribute.
98+ def self . format_with ( name , &block )
99+ raise ArgumentError , "You must has a block for formatters" unless block_given?
100+ formatters [ name . to_sym ] = block
101+ end
102+
103+ # Returns a hash of all formatters that are registered for this and it's ancestors.
104+ def self . formatters
105+ @formatters ||= { }
106+
107+ if superclass . respond_to? :formatters
108+ @formatters = superclass . formatters . merge ( @formatters )
109+ end
110+
111+ @formatters
112+ end
113+
96114 # This allows you to set a root element name for your representation.
97115 #
98116 # @param plural [String] the root key to use when representing
@@ -173,6 +191,10 @@ def exposures
173191 self . class . exposures
174192 end
175193
194+ def formatters
195+ self . class . formatters
196+ end
197+
176198 # The serializable hash is the Entity's primary output. It is the transformed
177199 # hash for the given data model and is used as the basis for serialization to
178200 # JSON and other formats.
@@ -207,7 +229,9 @@ def value_for(attribute, options = {})
207229 elsif exposure_options [ :format_with ]
208230 format_with = exposure_options [ :format_with ]
209231
210- if format_with . is_a? Symbol
232+ if format_with . is_a? ( Symbol ) && formatters [ format_with ]
233+ formatters [ format_with ] . call ( object . send ( attribute ) )
234+ elsif format_with . is_a? ( Symbol )
211235 self . send ( format_with , object . send ( attribute ) )
212236 elsif format_with . respond_to? :call
213237 format_with . call ( object . send ( attribute ) )
0 commit comments