lib/lotus/validations/attribute_definer.rb in lotus-validations-0.3.0 vs lib/lotus/validations/attribute_definer.rb in lotus-validations-0.3.1

- old
+ new

@@ -1,7 +1,8 @@ require 'set' require 'lotus/utils/attributes' +require 'lotus/validations/nested_attributes' module Lotus module Validations # Define attributes and their validations together # @@ -252,10 +253,20 @@ # signup.valid? # => true # # signup = Signup.new(password: 'short') # signup.valid? # => false def attribute(name, options = {}, &block) + _attribute(name, options, &block) + end + + # Define an attribute + # + # @see Lotus::Validations::AttributeDefiner#attribute + # + # @since 0.3.1 + # @api private + def _attribute(name, options = {}, &block) if block_given? define_nested_attribute(name, options, &block) validates(name, {}) else define_attribute(name, options) @@ -355,16 +366,12 @@ # Creates a validation class and configures it with the # given block. # # @since 0.2.4 # @api private - def build_validation_class(&block) - kls = Class.new do - include Lotus::Validations - end - kls.class_eval(&block) - kls + def build_validation_class(&blk) + NestedAttributes.fabricate(&blk) end end # Support for `Lotus::Entity` # @@ -399,17 +406,37 @@ base.class_eval do include EntityAttributeDefiner::InstanceMethods end end + # @return [Array<String>] + # + # @since 0.3.1 + # @api private + def defined_attributes + super + @defined_attributes.merge(attributes.map(&:to_s)) + end + + # Override attribute accessors function. + # + # @since 0.3.1 + # + # @api private + # @see Lotus::Model::Entity#define_attr_accessor + def define_attr_accessor(attr) + _attribute(attr) + super + end + # @since 0.2.3 # @api private # # @see Lotus::Validations::AttributeDefiner#attribute def attribute(name, options = {}) - super attributes name + super end # @since 0.2.3 # @api private # @@ -427,9 +454,15 @@ # @api private # # @see Lotus::Validations::AttributeDefiner#assign_attribute? def assign_attribute?(attr) super || attr.to_s == LOTUS_ENTITY_ID + end + + def initialize(attributes = {}) + super + @attributes.set(LOTUS_ENTITY_ID, id) + self.class.attribute(LOTUS_ENTITY_ID) end end end # Create a new instance with the given attributes