lib/representable.rb in representable-0.9.0 vs lib/representable.rb in representable-0.9.1

- old
+ new

@@ -1,7 +1,6 @@ require 'hooks/inheritable_attribute' - require 'representable/definition' require 'representable/nokogiri_extensions' module Representable @@ -15,17 +14,45 @@ inheritable_attr :explicit_representation_name # FIXME: move to Accessors. end end + # Reads values from +doc+ and sets properties accordingly. + def update_properties_from(doc) + self.class.representable_bindings.each do |ref| + next if block_given? and not yield ref # skip if block is false. # DISCUSS: will we keep that? + + value = ref.read(doc) + send(ref.definition.setter, value) + end + self + end + +private + # Compiles the document going through all properties. + def create_representation_with(doc) + self.class.representable_bindings.each do |ref| + next if block_given? and not yield ref # skip if block is false. # DISCUSS: will we keep that? + + value = public_send(ref.definition.getter) # DISCUSS: eventually move back to Ref. + ref.write(doc, value) if value + end + doc + end + + module ClassMethods # :nodoc: module Declarations def definition_class Definition end - + # Returns bindings for all properties. + def representable_bindings + representable_attrs.map {|attr| binding_for_definition(attr) } + end + # Declares a reference to a certain xml element, whether an attribute, a node, # or a typed collection of nodes. This method does not add a corresponding accessor # to the object. For that behavior see the similar methods: .xml_reader and .xml_accessor. # # == Sym Option @@ -181,35 +208,23 @@ # [:required] If true, throws RequiredElementMissing when the element isn't present # [:cdata] true for values which should be input from or output as cdata elements # [:to_xml] this proc is applied to the attributes value outputting the instance via #to_xml # def representable_property(*args) # TODO: make it accept 1-n props. - attr = representable_attr(*args) - add_reader(attr) - attr_writer(attr.accessor) + attr = add_representable_property(*args) + attr_reader(attr.getter) + attr_writer(attr.getter) end def representable_collection(name, options={}) options[:as] = [options[:as]].compact representable_property(name, options) end private - def representable_attr(name, options={}) - definition_class.new(name, options).tap do |attr| + def add_representable_property(*args) + definition_class.new(*args).tap do |attr| representable_attrs << attr - end - end - - def representable_reader(*syms, &block) - representable_attr(*syms, &block).each do |attr| - add_reader(attr) - end - end - - def add_reader(attr) - define_method(attr.accessor) do - instance_variable_get(attr.instance_variable_name) end end end module Accessors