lib/dynamoid/document.rb in dynamoid-3.0.0 vs lib/dynamoid/document.rb in dynamoid-3.1.0

- old
+ new

@@ -48,10 +48,15 @@ # @since 0.4.0 def write_capacity options[:write_capacity] || Dynamoid::Config.write_capacity end + # Returns the field name used to support STI for this table. + def inheritance_field + options[:inheritance_field] || :type + end + # Returns the id field for this class. # # @since 0.4.0 def hash_key options[:key] || :id @@ -100,11 +105,11 @@ # # @return [Dynamoid::Document] the new document # # @since 0.2.0 def build(attrs = {}) - attrs[:type] ? attrs[:type].constantize.new(attrs) : new(attrs) + choose_right_class(attrs).new(attrs) end # Does this object exist? # # @param [Mixed] id_or_conditions the id of the object or a hash with the options to filter from. @@ -249,22 +254,47 @@ begin new_attrs = Dynamoid.adapter.update_item(table_name, hash_key_value, options) do |t| attrs.each do |k, v| value_casted = TypeCasting.cast_field(v, attributes[k]) value_dumped = Dumping.dump_field(value_casted, attributes[k]) + t.set(k => value_dumped) end end + attrs_undumped = Undumping.undump_attributes(new_attrs, attributes) new(attrs_undumped) rescue Dynamoid::Errors::ConditionalCheckFailedException end end + def inc(hash_key_value, range_key_value=nil, counters) + options = if range_key + value_casted = TypeCasting.cast_field(range_key_value, attributes[range_key]) + value_dumped = Dumping.dump_field(value_casted, attributes[range_key]) + { range_key: value_dumped } + else + {} + end + + Dynamoid.adapter.update_item(table_name, hash_key_value, options) do |t| + counters.each do |k, v| + value_casted = TypeCasting.cast_field(v, attributes[k]) + value_dumped = Dumping.dump_field(value_casted, attributes[k]) + + t.add(k => value_dumped) + end + end + end + def deep_subclasses subclasses + subclasses.map(&:deep_subclasses).flatten end + + def choose_right_class(attrs) + attrs[inheritance_field] ? attrs[inheritance_field].constantize : self + end end # Initialize a new object. # # @param [Hash] attrs Attributes with which to create the object. @@ -279,9 +309,10 @@ run_callbacks :initialize do @new_record = true @attributes ||= {} @associations ||= {} + @attributes_before_type_cast ||= {} self.class.attributes.each do |_, options| if options[:type].is_a?(Class) && options[:default] raise 'Dynamoid class-type fields do not support default values' end