44require "action_controller"
55
66module HyperActiveForm
7+ ##
8+ # Base class for HyperActiveForm objects
9+ #
10+ # HyperActiveForm objects are simple ActiveModel objects that encapsulate
11+ # form logic and validations. They are designed to be subclassed and
12+ # customized to fit the needs of your application.
13+ #
714 class Base
815 include ActiveModel ::Model
916 include ActiveModel ::Attributes
@@ -12,6 +19,11 @@ class Base
1219
1320 define_model_callbacks :assign_form_attributes , :submit
1421
22+ # Defines to which object the form should delegate the active model methods
23+ # This is useful so `form_for`/`form_with` can automatically deduce the url and method to use
24+ #
25+ # @param klass [Class] the class of the object to proxy
26+ # @param object [Object] where to delegate the object to, for example: `:@user`
1527 def self . proxy_for ( klass , object )
1628 delegate :new_record? , :persisted? , :id , to : object
1729 singleton_class . delegate :model_name , to : klass
@@ -28,6 +40,12 @@ def perform
2840 raise NotImplementedError
2941 end
3042
43+ # Assigns the attributes of the form from the params
44+ # This method is called by the `submit` method, but can also be called
45+ # directly if you need to assign the attributes without submitting the form
46+ # for example if you want to refresh the form with new data
47+ #
48+ # @param params [Hash] the params to assign the attributes from
3149 def assign_form_attributes ( params )
3250 run_callbacks :assign_form_attributes do
3351 params = ActionController ::Parameters . new ( params ) unless params . is_a? ( ActionController ::Parameters )
@@ -38,6 +56,11 @@ def assign_form_attributes(params)
3856 end
3957 end
4058
59+ # Submits the form, assigning the attributes from the params,
60+ # running validations and calling the `perform` method if the form is valid
61+ #
62+ # @param params [Hash] the params to assign the attributes from
63+ # @return [Boolean] true if the form is valid and the `perform` method returned something truthy
4164 def submit ( params )
4265 run_callbacks :submit do
4366 assign_form_attributes ( params )
@@ -47,10 +70,17 @@ def submit(params)
4770 false
4871 end
4972
73+ # Same as `submit` but raises a `FormDidNotSubmitError` if the form is not valid
74+ #
75+ # @param params [Hash] the params to assign the attributes from
76+ # @return [Boolean] true if the form is valid and the `perform` method returned something truthy
5077 def submit! ( params )
5178 submit ( params ) || raise ( HyperActiveForm ::FormDidNotSubmitError )
5279 end
5380
81+ # Adds the errors from a model to the form
82+ #
83+ # @param model [ActiveModel::Model] the model to add the errors from
5484 def add_errors_from ( model )
5585 model . errors . each do |error |
5686 Array . wrap ( error . message ) . each { |e | errors . add ( error . attribute , e ) }
0 commit comments