lib/representable/coercion.rb in representable-1.8.5 vs lib/representable/coercion.rb in representable-2.0.0.rc1
- old
+ new
@@ -1,43 +1,35 @@
require "virtus"
-module Representable::Coercion
- class Coercer
- virtus_coercer = Virtus.respond_to?(:model) ? Virtus.model : Virtus
- include virtus_coercer
-
- def coerce(name, v) # TODO: test me.
- # set and get the value as i don't know where exactly coercion happens in virtus.
- send("#{name}=", v)
- send(name)
+module Representable
+ module Coercion
+ class Coercer
+ # This gets called when the :render_filter or :parse_filter option is evaluated.
+ # Usually the Coercer instance is an element in a Pipeline to allow >1 filters per property.
+ def call(value, doc, options)
+ Virtus::Attribute.build(options.binding[:type]).coerce(value)
+ end
end
- end
- # separate coercion object doesn't give us initializer and accessors in the represented object (with module representer)!
- def self.included(base)
- base.class_eval do
- extend ClassMethods
- # FIXME: use inheritable_attr when it's ready.
- representable_attrs.inheritable_array(:coercer_class) << Class.new(Coercer) unless representable_attrs.inheritable_array(:coercer_class).first
+
+ def self.included(base)
+ base.class_eval do
+ extend ClassMethods
+ register_feature Coercion
+ end
end
- end
- module ClassMethods
- def property(name, options={})
- return super unless options[:type]
+ module ClassMethods
+ def build_definition(name, options, &block) # Representable::Declarative
+ return super unless type = options[:type]
- representable_attrs.inheritable_array(:coercer_class).first.attribute(name, options[:type])
+ options[:pass_options] = true # TODO: remove, standard.
- # By using :getter we "pre-occupy" this directive, but we avoid creating accessors, which i find is the cleaner way.
- options[:exec_context] = :decorator
- options[:getter] = lambda { |*| coercer.coerce(name, represented.send(name)) }
- options[:setter] = lambda { |v,*| represented.send("#{name}=", coercer.coerce(name, v)) }
+ options[:render_filter] << coercer = Coercer.new
+ options[:parse_filter] << coercer
- super
+ super
+ end
end
end
-
- def coercer
- @coercer ||= representable_attrs.inheritable_array(:coercer_class).first.new
- end
-end
+end
\ No newline at end of file