Sha256: af3b6ef20b903f3edb43642102e8462e26f06da7dbaf0d67ddadfd2548fdcda8

Contents?: true

Size: 1.84 KB

Versions: 1

Compression:

Stored size: 1.84 KB

Contents

module Ciesta
  module InstanceMethods
    extend Forwardable

    # @!method assign
    # @!method assign!
    # @!method attributes
    # @see Ciesta::FieldList
    def_delegators :fields, :assign, :assign!, :attributes, :clear!

    # @!method errors
    # @see Ciesta::Validator
    def_delegators :validator, :errors

    # @!method sync
    # @!method sync!
    # @see Ciesta::Syncer
    def_delegators :syncer, :sync

    attr_accessor :object

    # Constructor
    #
    # @param [Object] object Object wich will be updated though this form
    def initialize(object = nil)
      @object = object
      clear!

      return if object.nil?

      values = fields.keys.each_with_object({}) do |key, mem|
        mem[key] = object.public_send(key) if object.respond_to?(key)
      end

      assign(values)
    end

    # Checks if form is valid
    #
    # @param [Hash] params Attrubutes to assign before validation
    #
    # @return [Boolean]
    def valid?(params = nil)
      assign(params) if params
      validator.valid?(attributes)
    end

    # Sync form attributes to object
    #
    # @see Ciesta::Syncer
    #
    # @param [Block] block Block wich will be yielded after synfing
    #
    # @raise Ciesta::ModelNotPresent
    # @raise Ciesta::FormNotValid
    # @return [Boolean]
    def sync!(&block)
      raise Ciesta::FormNotValid, "Form is not valid" unless valid?

      syncer.sync!(&block)
    end

    private

    # Sync class for form
    #
    # @api private
    # @return [Ciesta::Syncer]
    def syncer
      @syncer ||= Ciesta::Syncer.new(object, fields)
    end

    # Returns form validator
    #
    # @api private
    # @see Ciesta::Form.validator
    def validator
      self.class.validator
    end

    # Returns field list
    #
    # @api private
    # @see Ciesta::Form.fields
    def fields
      self.class.fields
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
ciesta-0.3.2 lib/ciesta/instance_methods.rb