lib/alba/resource.rb in alba-3.1.0 vs lib/alba/resource.rb in alba-3.2.0

- old
+ new

@@ -20,21 +20,21 @@ # `setup` method is meta-programmatically defined here for performance. # @private def self.included(base) # rubocop:disable Metrics/MethodLength super - setup_method_body = +'private def _setup;' base.class_eval do # Initialize + setup_method_body = +'private def _setup;' INTERNAL_VARIABLES.each do |name, initial| instance_variable_set(:"@#{name}", initial.dup) unless instance_variable_defined?(:"@#{name}") setup_method_body << "@#{name} = self.class.#{name};" end - base.define_method(:encode, Alba.encoder) + setup_method_body << 'end' + class_eval(setup_method_body, __FILE__, __LINE__ + 1) + define_method(:encode, Alba.encoder) end - setup_method_body << 'end' - base.class_eval(setup_method_body, __FILE__, __LINE__ + 1) base.include InstanceMethods base.extend ClassMethods end # Instance methods @@ -482,9 +482,29 @@ end @_transform_type = type @_transforming_root_key = root @_key_transformation_cascade = cascade + end + + # Transform keys as specified type AFTER the class is defined + # Note that this is an experimental API and may be removed/changed + # + # @see #transform_keys + def transform_keys!(type) + dup.class_eval do + transform_keys(type, root: @_transforming_root_key, cascade: @_key_transformation_cascade) + + if @_key_transformation_cascade + # We need to update key transformation of associations and nested attributes + @_attributes.each_value do |attr| + next unless attr.is_a?(Association) || attr.is_a?(NestedAttribute) + + attr.key_transformation = type + end + end + self # Return the new class + end end # Sets key for collection serialization # # @param key [String, Symbol]