compony 0.2.0 → 0.2.2

Sign up to get free protection for your applications and to get access to all the features.
Files changed (91) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +25 -0
  3. data/Gemfile.lock +3 -3
  4. data/README.md +1397 -33
  5. data/Rakefile +6 -2
  6. data/TODO.md +1 -0
  7. data/VERSION +1 -0
  8. data/app/controllers/compony_controller.rb +3 -1
  9. data/compony.gemspec +7 -7
  10. data/config/locales/fr.yml +33 -0
  11. data/doc/ComponentGenerator.html +231 -0
  12. data/doc/Components.html +105 -0
  13. data/doc/ComponentsGenerator.html +203 -0
  14. data/doc/Compony/Component.html +2098 -0
  15. data/doc/Compony/ComponentMixins/Default/Labelling.html +406 -0
  16. data/doc/Compony/ComponentMixins/Default/Standalone/ResourcefulVerbDsl.html +539 -0
  17. data/doc/Compony/ComponentMixins/Default/Standalone/StandaloneDsl.html +588 -0
  18. data/doc/Compony/ComponentMixins/Default/Standalone/VerbDsl.html +577 -0
  19. data/doc/Compony/ComponentMixins/Default/Standalone.html +692 -0
  20. data/doc/Compony/ComponentMixins/Default.html +126 -0
  21. data/doc/Compony/ComponentMixins/Resourceful.html +1193 -0
  22. data/doc/Compony/ComponentMixins.html +126 -0
  23. data/doc/Compony/Components/Button.html +293 -0
  24. data/doc/Compony/Components/Destroy.html +384 -0
  25. data/doc/Compony/Components/Edit.html +462 -0
  26. data/doc/Compony/Components/Form.html +1112 -0
  27. data/doc/Compony/Components/New.html +462 -0
  28. data/doc/Compony/Components/WithForm.html +528 -0
  29. data/doc/Compony/Components.html +126 -0
  30. data/doc/Compony/ControllerMixin.html +136 -0
  31. data/doc/Compony/Engine.html +133 -0
  32. data/doc/Compony/MethodAccessibleHash.html +453 -0
  33. data/doc/Compony/ModelFields/Anchormodel.html +383 -0
  34. data/doc/Compony/ModelFields/Association.html +613 -0
  35. data/doc/Compony/ModelFields/Attachment.html +305 -0
  36. data/doc/Compony/ModelFields/Base.html +1066 -0
  37. data/doc/Compony/ModelFields/Boolean.html +232 -0
  38. data/doc/Compony/ModelFields/Color.html +299 -0
  39. data/doc/Compony/ModelFields/Currency.html +232 -0
  40. data/doc/Compony/ModelFields/Date.html +232 -0
  41. data/doc/Compony/ModelFields/Datetime.html +232 -0
  42. data/doc/Compony/ModelFields/Decimal.html +154 -0
  43. data/doc/Compony/ModelFields/Email.html +240 -0
  44. data/doc/Compony/ModelFields/Float.html +154 -0
  45. data/doc/Compony/ModelFields/Integer.html +154 -0
  46. data/doc/Compony/ModelFields/Percentage.html +232 -0
  47. data/doc/Compony/ModelFields/Phone.html +301 -0
  48. data/doc/Compony/ModelFields/RichText.html +232 -0
  49. data/doc/Compony/ModelFields/String.html +154 -0
  50. data/doc/Compony/ModelFields/Text.html +154 -0
  51. data/doc/Compony/ModelFields/Time.html +154 -0
  52. data/doc/Compony/ModelFields/Url.html +240 -0
  53. data/doc/Compony/ModelFields.html +126 -0
  54. data/doc/Compony/ModelMixin.html +524 -0
  55. data/doc/Compony/RequestContext.html +791 -0
  56. data/doc/Compony/Version.html +139 -0
  57. data/doc/Compony/ViewHelpers.html +443 -0
  58. data/doc/Compony.html +2156 -0
  59. data/doc/ComponyController.html +124 -0
  60. data/doc/_index.html +569 -0
  61. data/doc/class_list.html +51 -0
  62. data/doc/css/common.css +1 -0
  63. data/doc/css/full_list.css +58 -0
  64. data/doc/css/style.css +497 -0
  65. data/doc/file.README.html +1565 -0
  66. data/doc/file_list.html +56 -0
  67. data/doc/frames.html +17 -0
  68. data/doc/imgs/intro-example-destroy.png +0 -0
  69. data/doc/imgs/intro-example-edit.png +0 -0
  70. data/doc/imgs/intro-example-index.png +0 -0
  71. data/doc/imgs/intro-example-new.png +0 -0
  72. data/doc/imgs/intro-example-show.png +0 -0
  73. data/doc/index.html +1565 -0
  74. data/doc/js/app.js +314 -0
  75. data/doc/js/full_list.js +216 -0
  76. data/doc/js/jquery.js +4 -0
  77. data/doc/method_list.html +1435 -0
  78. data/doc/resourceful_lifecycle.png +0 -0
  79. data/doc/top-level-namespace.html +112 -0
  80. data/lib/compony/component.rb +2 -1
  81. data/lib/compony/component_mixins/default/standalone/resourceful_verb_dsl.rb +1 -1
  82. data/lib/compony/component_mixins/default/standalone/standalone_dsl.rb +14 -3
  83. data/lib/compony/component_mixins/default/standalone/verb_dsl.rb +14 -5
  84. data/lib/compony/component_mixins/default/standalone.rb +10 -3
  85. data/lib/compony/components/form.rb +6 -1
  86. data/lib/compony/components/with_form.rb +14 -1
  87. data/lib/compony/model_fields/anchormodel.rb +0 -22
  88. data/lib/compony/model_mixin.rb +12 -2
  89. data/lib/compony/version.rb +1 -7
  90. data/logo.svg +133 -0
  91. metadata +83 -6
data/README.md CHANGED
@@ -1,33 +1,1397 @@
1
- TODO: Write this
2
-
3
- Notes:
4
-
5
- - `model` is an ApplicationModel or similar (e.g. ActiveType, but not guarantted to work at this point), `.model_name` is important
6
- - `data` can be model or models
7
- - To redirect instead of rendering, use `before_render` if the redirect is conditional (e.g. if validation passes), or `respond` if always redirecting.
8
- - As a rule of thumb, use `before_render` if there is a `content` block (even by inheritance) and `respond` otherwise.
9
- - To protect a custom controller by compony authentication, use in the controller: `before_action Compony.authentication_before_action`
10
-
11
- Feature sets:
12
-
13
- - Base feature: Components
14
- - replace routes, views and controllers
15
- - actions
16
- - params and nesting
17
- - skipping authentication
18
- - lifecycle
19
- - standalone
20
- - resourcefulness
21
- - authorization
22
- - Buttons and links
23
- - labelling
24
- - coloring
25
- - Fields and field groups
26
- - Feasibility
27
- - Premade components
28
- - button
29
- - destroy
30
- - form
31
- - with_form
32
- - new
33
- - edit
1
+ <img src="logo.svg" height=250 alt="Compony logo"/>
2
+
3
+ - To see the README including images, refer to https://github.com/kalsan/compony
4
+ - To see the class documentation, refer to https://www.rubydoc.info/github/kalsan/compony
5
+
6
+ # Introduction
7
+
8
+ Compony is a Gem that allows you to write your Rails application in component-style fashion. It combines a controller action and route along with its view into a single Ruby class. This allows writing much DRYer code, using inheritance even in views and much easier refactoring for your Rails applications, helping you to keep the code clean as the application evolves.
9
+
10
+ Compony's key aspects:
11
+
12
+ - A Compony component is a single class that exports route(s), controller action(s) and a view to Rails.
13
+ - Refactor common logic into your own components and inherit from them to DRY up your code.
14
+ - Compony's powerful model mixin allows you to define metadata in your models and react to them. Examples:
15
+ - Compony fields capture attributes that should be made visible in your UI. They allow you to implement formatting behavior and parameter sanitization for various types, e.g. URLs, phone numbers, colors etc. ready to be used in your lists, detail panels, or forms.
16
+ - Compony's feasibility framework allows you to prohibit actions based on conditions, along with an error message. This causes all buttons pointing to that action to be disabled with a meaningful error message.
17
+ - Compony only structures your code, but provides no style whatsoever. It is like a bookshelf rather than a reader's library. You still implement your own layouts, CSS and Javascript to define the behavior of your front-end.
18
+ - Using Compony, you **can** write your application as components, but it is still possible to have regular routes, controllers and views side-to-side to it. This way, you can migrate your applications to Compony little by little and enter and leave the Compony world as you please. It is also possible to render Compony components from regular views and vice versa.
19
+ - Compony is built for Rails 7 and fully supports Stimulus and Turbo Drive. Turbo Frames and Streams are not yet targeted, so Compony is currently meant for websites where every click triggers a "full page load" (in quotes because they are not actually full page loads due to Turbo Drive).
20
+ - Compony uses CanCanCan (https://github.com/CanCanCommunity/cancancan) for authorization but does not provide an authentication mechanism. You can easily build your own by creating login/logout components that manage cookies, and configure Compony to enforce authentication using the `Compony.authentication_before_action` setter.
21
+
22
+ ## State of the project
23
+
24
+ I am actively using this framework in various applications and both performance and reliability are good. However, the project is at an early stage and is lacking peer reviews and especially automatic testing, such as unit and integration tests. Also, expect there to be (documented) breaking changes in the future, as the API will likely be further refined, resulting in renamings and deprecation of various methods.
25
+
26
+ ## Example
27
+
28
+ To get you a rough idea what working with Compony feels like, let's look at a small dummy application using Compony from scratch, to make this example as explicit as possible. In practice, much of the logic shown here would be moved to abstract components that you can inherit from.
29
+
30
+ The example is meant to be read top-down and information will mostly not be repeated. Comments will give you a rough idea of what's going on on each line. The features are more completely documented in subsequent chapters.
31
+
32
+ Let's implement a simple user management page with Compony. User's have a name, an integer age, a comment, as well as a role (which we will conveniently model using `AnchorModel`: https://github.com/kalsan/anchormodel). We want to be able to list, show, create, edit and destroy users. Users having the role Admin shall not be destroyed.
33
+
34
+ ### The User model
35
+
36
+ We'll assume a model that has the standard Rails schema:
37
+
38
+ ```ruby
39
+ create_table 'users', force: :cascade do |t|
40
+ t.string 'name'
41
+ t.string 'comment'
42
+ t.integer 'age'
43
+ t.datetime 'created_at', null: false
44
+ t.datetime 'updated_at', null: false
45
+ t.string 'role', default: 'guest', null: false
46
+ end
47
+ ```
48
+
49
+ ```ruby
50
+ class User < ApplicationRecord
51
+ # Refer to https://github.com/kalsan/anchormodel
52
+ belongs_to_anchormodel :role
53
+
54
+ # Fields define which attributes are relevant in the GUI and how they should be presented.
55
+ field :name, :string
56
+ field :age, :integer
57
+ field :comment, :string
58
+ field :role, :anchormodel
59
+ field :created_at, :datetime
60
+ field :updated_at, :datetime
61
+
62
+ # The method `label` must be implemented on all Compony models. Instead of this method, we could also rename the column :name to :label.
63
+ def label
64
+ name
65
+ end
66
+
67
+ # This is how we tell Compony that admins are not to be destroyed.
68
+ prevent :destroy, 'Cannot destroy admins' do
69
+ role == Role.find(:admin)
70
+ end
71
+ end
72
+ ```
73
+
74
+ ### The Show component
75
+
76
+ This components loads a user by reading the param `id`. It then displays a simple table showing all the fields defined above.
77
+
78
+ We will implement this component on our own, giving you an insight into many of Compony's mechanisms:
79
+
80
+ ```ruby
81
+ # All components (except abstract ones) must be placed in the `Components` namespace living under `app/components`.
82
+ # They must be nested in another namespace, called "family" (here, `Users`), followed by the component's name (here, `Show`).
83
+ class Components::Users::Show < Compony::Component
84
+ # The Resourceful mixin causes a component to automatically load a model from the `id` parameter and store it under `@data`.
85
+ # The model's class is inferred from the component's name: `Users::Show` -> `User`
86
+ include Compony::ComponentMixins::Resourceful
87
+
88
+ # Components are configured in the `setup` method, which prevents loading order issues.
89
+ setup do
90
+ # The DSL call `label` defines what is the title of the component and which text is displayed on links as well as buttons pointing to it.
91
+ # It accepts different formats and takes a block. Given that this component always loads one model, the block must take an argument which is the model.
92
+ # The argument must be provided by links and buttons pointing to this component.
93
+ label(:short) { |_u| 'Show' } # The short format is suitable for e.g. a button in a list of users.
94
+ label(:long) { |u| "Show user #{u.label}" } # The long format is suitable e.g. in a link in a text about this user.
95
+
96
+ # Actions point to other components. They have a name that is used to identify them (e.g. in the `prevent` call above) and a block returning a button.
97
+ # Compony buttons take the name to an action and either a family name or instance, e.g. a Rails model instance.
98
+ # Whether or not an instance must be passed is defined by the component the button is pointing to (see the comment for `label` earlier in the example).
99
+ action(:index) { Compony.button(:index, :users) } # This points to `Components::Users::Index` without passing a model (because it's an index).
100
+ action(:edit) { Compony.button(:edit, @data) } # This points to `Components::Users::Edit` for the currently loaded model. This also checks feasibility.
101
+
102
+ # When a standalone config is present, Compony creates one or multiple Rails routes. Components without standalone config must be nested within others.
103
+ standalone path: 'users/show/:id' do # This specifies the path to this component.
104
+ verb :get do # This speficies that a GET route should be created for the path specified above.
105
+ authorize { true } # Immediately after loading the model, this is called to check for authorization. `true` means that anybody can get access.
106
+ end
107
+ end
108
+
109
+ # After loading the model and passing authorization, the `content` block is evaluated. This is Compony's equivalent to Rails' views.
110
+ # Inside the `content` block, the templating Gem Dyny (https://github.com/kalsan/dyny) is used, allowing you to write views in plain Ruby.
111
+ content do
112
+ h3 @data.label # Display a <h3> title
113
+ table do # Open a <table> tag
114
+ tr do # Open a <tr> tag
115
+ # Iterate over all the fields defined in the model above and display its translated label (this uses Rails' `human_attribute_name`), e.g. "Name".
116
+ @data.fields.each_value { |field| th field.label }
117
+ end # Closing </tr>
118
+ tr do
119
+ # Iterate over the fields again and call `value_for` which formats each field's value according to the field type.
120
+ @data.fields.each_value { |field| td field.value_for(@data) }
121
+ end
122
+ end
123
+ end
124
+ end
125
+ end
126
+ ```
127
+
128
+ Here is what our Show component looks like when we have a layout with the bare minimum and no styling at all:
129
+
130
+ ![Screenshot of our component with an absolutely minimal layout](doc/imgs/intro-example-show.png)
131
+
132
+ It is important to note that actions, buttons, navigation, notifications etc. are handled by the application layout. In this and the subsequent screenshots, we explicitely use minimalism, as it makes the generated HTML clearer.
133
+
134
+ ### The Destroy component
135
+
136
+ Compony has a built-in abstract `Destroy` component which displays a confirmation message and destroys the record if the verb is `DELETE`. This is a good example for how DRY code can become for "boring" components. Since everything is provided with an overridable default, components without special logic can actually be left blank:
137
+
138
+ ```ruby
139
+ class Components::Users::Destroy < Compony::Components::Destroy
140
+ end
141
+ ```
142
+
143
+ Note that this component is fully functional. All is handled by the class it inherits from:
144
+
145
+ ![Screenshot of the destroy component](doc/imgs/intro-example-destroy.png)
146
+
147
+ ### The New component and the Form component
148
+
149
+ Compony also has a pre-built abstract `New` component that handles routing and resource manipulation. It combines the controller actions `new` and `create`, depending on the HTTP verb of the request. Since it's pre-built, any "boring" code can be omitted and our `New` components looks like this:
150
+
151
+ ```ruby
152
+ class Components::Users::New < Compony::Components::New
153
+ end
154
+ ```
155
+
156
+ By default, this component looks for another component called `Form` in the same directory, which can look like this:
157
+
158
+ ```ruby
159
+ class Components::Users::Form < Compony::Components::Form
160
+ setup do
161
+ # This mandatory DSL call prepares and opens a form in which you can write your HTML in Dyny.
162
+ # The form is realized using the simple_form Gem (https://github.com/heartcombo/simple_form).
163
+ # Inside this block, more DSL calls are available, such as `field`, which automatically generates
164
+ # a suitable simple_form input from the field specified in the model.
165
+ form_fields do
166
+ concat field(:name) # `field` checks the model to find out that a string input is needed here. `concat` is the Dyny equivalent to ERB's <%= %>.
167
+ concat field(:age)
168
+ concat field(:comment)
169
+ concat field(:role) # Compony has built-in support for Anchormodel and as the model declares `role` to be of type `anchormodel`, a select is rendered.
170
+ end
171
+
172
+ # This DSL call is mandatory as well and automatically generates strong param validation for this form.
173
+ # The generated underlying implementation is Schemacop V3 (https://github.com/sitrox/schemacop/blob/master/README_V3.md).
174
+ schema_fields :name, :age, :comment, :role
175
+ end
176
+ end
177
+ ```
178
+
179
+ This is enough to render a fully functional form that creates new users:
180
+
181
+ ![New form](doc/imgs/intro-example-new.png)
182
+
183
+ ### The Edit component
184
+
185
+ Just like `New`, `Edit` is a pre-built component that handles routing and resource manipulation for editing models, combinding the controller actions `edit` and `update` depending on the HTTP verb. It uses that same `Form` component we wrote above and thus the code is as simple as:
186
+
187
+ ```ruby
188
+ class Components::Users::Edit < Compony::Components::Edit
189
+ end
190
+ ```
191
+
192
+ It then looks like this:
193
+
194
+ ![Edit form](doc/imgs/intro-example-edit.png)
195
+
196
+ ### The Index component
197
+
198
+ This component should list all users and provide buttons to manage them. We'll build it from scratch and make it resourceful, where `@data` holds the ActiveRecord relation.
199
+
200
+ ```ruby
201
+ class Components::Users::Index < Compony::Component
202
+ # Making the component resourceful enables a few features for dealing with @data.
203
+ include Compony::ComponentMixins::Resourceful
204
+
205
+ setup do
206
+ label(:all) { 'Users' } # This sets all labels (long and short) to 'Users'. When pointing to this component using buttons, we will not provide a model.
207
+ standalone path: 'users' do # The path is simply /users, without a param. This conflicts with `Resourceful`, which we will fix in `load_data`.
208
+ verb :get do
209
+ authorize { true }
210
+ end
211
+ end
212
+
213
+ # This DSL call is specific to resourceful components and overrides how a model is loaded.
214
+ # The block is called before authorization and must assign a model or collection to `@data`.
215
+ load_data { @data = User.all }
216
+
217
+ content do
218
+ h4 'Users:' # Provide a title
219
+ # Provide a button that creates a new user. Note that we must write `:users` (plural) because the component's family is `Users`.
220
+ concat compony_button(:new, :users) # The `Users::New` component does not take a model, thus we just pass the symbol `:users`, not a model.
221
+
222
+ div class: 'users' do # Opening tag <div class="users">
223
+ @data.each do |user| # Iterate the collection
224
+ div class: 'user' do # For each element, open another div
225
+ User.fields.values.each do |field| # For each user, iterate all fields
226
+ span do # Open a <span> tag
227
+ concat "#{field.label}: #{field.value_for(user)} " # Display the field's label and apply it to value, as we did in the Show component.
228
+ end
229
+ end
230
+ # For each user, add three buttons show, edit, destroy. The method `with_button_defaults` applies its arguments to every `compony_button` call.
231
+ # The option `format: :short` causes the button to call the target component's `label(:short) {...}` label function.
232
+ Compony.with_button_defaults(label_opts: { format: :short }) do
233
+ concat compony_button(:show, user) # Now equivalent to: `compony_button(:show, user, label_opts: { format: :short })`
234
+ concat compony_button(:edit, user)
235
+ concat compony_button(:destroy, user)
236
+ end
237
+ end
238
+ end
239
+ end
240
+ end
241
+ end
242
+ end
243
+ ```
244
+
245
+ The result looks like this:
246
+
247
+ ![Index component](doc/imgs/intro-example-index.png)
248
+
249
+ Note how the admin's delete button is disabled due to the feasibility framework. Pointing the mouse at it causes a tooltip saying: "Cannot destroy admins.", as specified in the model's prevention.
250
+
251
+ # Installation
252
+
253
+ ## Installing Compony
254
+
255
+ First, add Compony to your Gemfile:
256
+
257
+ ```ruby
258
+ gem 'compony'
259
+ ```
260
+
261
+ Then run `bundle install`.
262
+
263
+ Create the directory `app/components`.
264
+
265
+ In `app/models/application_record.rb`, add the following line below `primary_abstract_class`:
266
+
267
+ ```ruby
268
+ include Compony::ModelMixin
269
+ ```
270
+
271
+ ## Installing CanCanCan
272
+
273
+ Create the file `app/models/ability.rb` with the following content:
274
+
275
+ ```ruby
276
+ class Ability
277
+ include CanCan::Ability
278
+
279
+ def initialize(_user)
280
+ can :manage, :all
281
+ end
282
+ end
283
+ ```
284
+
285
+ This is an initial dummy ability that allows anyone to do anything. Most likely, you will want to adjust the file. For documentation, refer to [https://github.com/CanCanCommunity/cancancan/](https://github.com/CanCanCommunity/cancancan/).
286
+
287
+ ## Optional: installing anchormodel
288
+
289
+ To take advantage of the anchormodel integration, follow the installation instructions under [https://github.com/kalsan/anchormodel/](https://github.com/kalsan/anchormodel/).
290
+
291
+ # Usage
292
+
293
+ Compony components are nestable elements that are capable of replacing Rails' routes, views and controllers. They structure code for data manipulation, authentication and rendering into a single class that can easily be subclassed. This is achieved with Compony's DSL that provides a readable and overridable way to store your logic.
294
+
295
+ Just like Rails, Compony is opinionated and you are advised to structure your code according to the examples and explanations. This makes it easier for others to dive into existing code.
296
+
297
+ ## A basic (bare) component
298
+
299
+ ### Naming
300
+
301
+ Compony components must be named according to the pattern `Components::FamilyName::ComponentName`.
302
+
303
+ - The family name should be pluralized and is analog to naming a Rails controller. For instance, when you would create a `UsersController` in plain Rails, the Compony family equivalent is `Users`.
304
+ - The component name is the Compony analog to a Rails action.
305
+
306
+ Example: If your plain Rails `UsersController` has an action `show`, the equivalent Compony component is `Components::Users::Show` and is located under `app/components/users/show.rb`.
307
+
308
+ If you have abstract components (i.e. components that your app never uses directly, but which you inherit from), you may name and place them arbitrarily.
309
+
310
+ ### Initialization, manual instantiation and rendering
311
+
312
+ You will rarely have to override `def initialize` of a component, as most of your code will go into the component's `setup` block as explained below. However, when you do, make sure to forward all default arguments to the parent class, as they are essential to the component's function:
313
+
314
+ ```ruby
315
+ def initialize(some_positional_argument, another=nil, *args, some_keyword_argument:, yetanother: 42, **kwargs, &block)
316
+ super(*args, **kwargs, &block) # Typically you should call this first
317
+ @foo = some_positional_argument
318
+ @bar = another
319
+ @baz = some_keyword_argument
320
+ @stuff = yetanother
321
+ end
322
+ ```
323
+
324
+ Typically, your components will be instantiated and rendered by Compony through the "standalone" feature explained below. Nonetheless, it is possible to do so manually as well, for instance if you'd like to render a component from within an existing view in your application:
325
+
326
+ ```erb
327
+ <% index_users_comp = Components::Users::Index.new %>
328
+ <%= index_users_comp.render(controller) %>
329
+ ```
330
+
331
+ Note that rendering a component always requires the controller as an argument. It also possible to pass an argument `locals` that will be made available to `render` (see below):
332
+
333
+ ```erb
334
+ <% index_users_comp = Components::Users::Index.new %>
335
+ <%= index_users_comp.render(controller, locals: { weather: :sunny }) %>
336
+ ```
337
+
338
+ ### Setup
339
+
340
+ Every component must call the static method `setup` which will contain most of the code of your components. This can be achieved either by a call directly from your class, or by inheriting from a component that calls `setup`. If both classes call the method, the inherited class' `setup` is run first and the inheriting's second, thus, the child class can override setup properties of the parent class.
341
+
342
+ Call setup as follows:
343
+
344
+ ```ruby
345
+ class Components::Users::Show < Compony::Component
346
+ setup do
347
+ # Your setup code goes here
348
+ end
349
+ end
350
+ ```
351
+
352
+ The code in setup is run at the end the component's initialization. In this block, you will call a number of methods that define the component's behavior and which we will explain now.
353
+
354
+ #### Labelling
355
+
356
+ This defines a component's label, both as seen from within the component and from the outside. You can query the label in order to display it as a title in your component. Links and buttons to components will also display the same label, allowing you to easily rename a component, including any parts of your UI that point to it.
357
+
358
+ Labels come in different formats, short and long, with long being the default. Define them as follows if your component is about a specific object, for instance a show component for a specific user:
359
+
360
+ ```ruby
361
+ setup do
362
+ label(:short) { |user| user.label } # Assuming your User model has a method or attribute `label`.
363
+ label(:long) { |user| "Displaying user #{user.label}" } # In practice, you'd probably use I18n.t or FastGettext here to deal with translations.
364
+
365
+ # Or use this short hand to set both long and short label to the user's label:
366
+ label(:all) { |user| user.label }
367
+ end
368
+ ```
369
+
370
+ To read the label, from within the component or from outside, proceed as follows:
371
+
372
+ ```ruby
373
+ label(User.first) # This returns the long version: "Displaying user John Doe".
374
+ label(User.first, format: :short) # This returns the short version "John Doe".
375
+ ```
376
+
377
+ It is important to note that since your label block takes an argument, you must provide the argument when reading the label (exception: if the component implements the method `data` returning an object, the argument can be omitted and the label block will be provided that object). Only up to one argument is supported.
378
+
379
+ Here is an example on how labelling looks like for a component that is not about a specific object, such as an index component for users:
380
+
381
+ ```ruby
382
+ setup do
383
+ label(:long) { 'List of users' }
384
+ label(:short) { 'List' }
385
+ end
386
+ ```
387
+
388
+ And to read those:
389
+
390
+ ```ruby
391
+ label # "List of users"
392
+ label(format: :short) # "List"
393
+ ```
394
+
395
+ If you do not define any labels, Compony will fallback to the default which is using Rail's `humanize` method to build a name from the family and component name, e.g. "index users".
396
+
397
+ Additionally, components can specify an icon and a color. These are not used by Compony directly and it is up to you to to define how and where to use them. Example:
398
+
399
+ ```ruby
400
+ setup do
401
+ color { '#AA0000' }
402
+ icon { %i[fa-solid circle] }
403
+ end
404
+ ```
405
+
406
+ To retrieve them from outside the component, use:
407
+
408
+ ```ruby
409
+ my_component.color # '#AA0000'
410
+ my_component.icon # [:'fa-solid', :circle]
411
+ ```
412
+
413
+ #### Providing content
414
+
415
+ Basic components do not come with default content. Instead, you must call the method `content` inside the setup block and provide a block containing your view. It will be evaluated inside a `RequestContext` (more on that later).
416
+
417
+ In this block, provide the HTML to be generated using Dyny: [https://github.com/kalsan/dyny](https://github.com/kalsan/dyny)
418
+
419
+ Here is an example of a component that renders a title along with a paragraph:
420
+
421
+ ```ruby
422
+ setup do
423
+ label(:all) { 'Welcome' }
424
+ content do
425
+ h1 'Welcome to my basic component'
426
+ para "It's not much, but it's honest work."
427
+ end
428
+ end
429
+ ```
430
+
431
+ If a subclass component calls `content`, it overwrites the block of the parent class, replacing the entire content. To make overwriting more granular, you can use `add_content` instead of `content`. This method can be called multiple times to create an array of content. If no argument is specified, the new content is placed at the bottom. Otherwise, it is inserted at the indicated position. Example:
432
+
433
+ ```ruby
434
+ setup do
435
+ content do
436
+ h1 'Welcome to my basic component'
437
+ end
438
+ add_content do
439
+ para 'Thank you and see you tomorrow.'
440
+ end
441
+ add_content 1 do
442
+ para 'This paragraph is inserted between the others.'
443
+ end
444
+ end
445
+ ```
446
+
447
+ The result is the h1 with index 0, then the paragraph reading "This paragraph..." with index 1, and finally "Thank you..." with index 2.
448
+
449
+ #### Redirecting away / Intercepting rendering
450
+
451
+ Immediately before the `content` block(s) are evaluated, another block is evaluated if present: `before_render`. If this block creates a reponse body in the Rails controller, the content blocks are skipped.
452
+
453
+ This is useful for redirecting. Here is an example of a component that provides a restaurant's lunch menu, but redirects to the menu overview page instead if it's not lunch time:
454
+
455
+ ```ruby
456
+ setup do
457
+ label(:all){ 'Lunch menu' }
458
+
459
+ before_render do
460
+ current_time = Time.zone.now
461
+ if current_time.hour >= 11 && current_time.hour < 14
462
+ flash.notice = "Sorry, it's not lunch time."
463
+ redirect_to all_menus_path
464
+ end
465
+ end
466
+
467
+ content do # This is entirely skipped if it's not lunch time.
468
+ h1 label
469
+ para 'Today we have spaghetti.'
470
+ end
471
+ end
472
+ ```
473
+
474
+ ## Standalone
475
+
476
+ As stated earlier, Compony can generate routes to your components. This is achieved by using the standalone DSL inside the setup block. The first step is calling the method `standalone` with a path. Inside this block, you will then specify which HTTP verbs (e.g. GET, PATCH etc.) the component should listen to. As soon as both are specified, Compony will generate an appropriate route.
477
+
478
+ Assume that you want to create a simple component `statics/welcome.rb` that displays a static welcome page. The component should be exposed under the route `'/welcome'` and respond to the GET method. Here is the complete code for making this happen:
479
+
480
+ ```ruby
481
+ # app/components/statics/welcome.rb
482
+ class Components::Statics::Welcome < Compony::Component
483
+ setup do
484
+ label(:all) { 'Welcome' }
485
+
486
+ standalone path: 'welcome' do
487
+ verb :get do
488
+ authorize { true }
489
+ end
490
+ end
491
+
492
+ content do
493
+ h1 'Welcome to my dummy site!'
494
+ end
495
+ end
496
+ end
497
+ ```
498
+
499
+ This is the minimal required code for standalone. For security, every verb config must provide an `authorize` block that specifies who has access to this standalone verb. The block is given the request context and is expected to return either true (access ok) or false (causing the request to fail with `Cancan::AccessDenied`).
500
+
501
+ Typically, you would use this block to check authorization using the CanCanCan gem, such as `authorize { can?(:read, :welcome) }`. However, since we skip authentication in this simple example, we pass `true` to allow all access.
502
+
503
+ The standalone DSL has more features than those presented in the minimal example above. Excluding resourceful features (which we will cover below), the full list is:
504
+
505
+ - `standalone` can be called multiple times, for components that need to expose multiple paths, as described below. Inside each `standalone` call, you can call:
506
+ - `skip_authentication!` which disables authentication, in case you provided some. You need to implement `authorize` regardless.
507
+ - `layout` which takes the file name of a Rails layout and defaults to `layouts/application`. Use this to have your Rails application look differently depending on the component.
508
+ - `verb` which takes an HTTP verb as a symbol, one of: `%i[get head post put delete connect options trace patch]`. `verb` can be called up to once per verb. Inside each `verb` call, you can call (in the non-resourceful case):
509
+ - `authorize` is mandatory and explained above.
510
+ - `respond` can be used to implement special behavior that in plain Rails would be placed in a controller action. The default, which calls `before_render` and the `content` blocks, is usually the right choice, so you will rarely implement `respond` on your own. See below how `respond` can be used to handle different formats or redirecting clients. **Caution:** `authorize` is evaluated in the default implementation of `respond`, so when you override that block, you must perform authorization yourself!
511
+
512
+ ### Exposing multiple paths in the same component (calling standalone multiple times)
513
+
514
+ If your component loads data dynamically from a JavaScript front-end (e.g. implemented via Stimulus), you will find yourself in the situation where you need an extra route for a functionality that inherently belongs to the same component. Example use cases would be search fields that load data as the user types, maps that load tiles, dynamic photo galleries etc.
515
+
516
+ In this case, you can call `standalone` a second time and provide a name for your extra route:
517
+
518
+ ```ruby
519
+ setup do
520
+ # Regular route for rendering the content
521
+ standalone path: 'map/viewer' do
522
+ verb :get do
523
+ authorize { true }
524
+ end
525
+ end
526
+
527
+ # Extra route for loading tiles via AJAX
528
+ standalone :tiles, path: 'map/viewer/tiles' do
529
+ verb :get do
530
+ respond do # Again: overriding `respond` skips authorization! This is why we don't need to provide an `authorize` block here.
531
+ controller.render(json: MapTiler.load(params, current_ability)) # current_ability is provided by CanCanCan and made available by Compony.
532
+ end
533
+ end
534
+ end
535
+
536
+ # More code for labelling, content etc.
537
+ end
538
+ ```
539
+
540
+ Please note that the idea here is to package things that belong together, not to provide different kinds of content in a single component. For displaying different pages, use multiple components and have each expose a single route.
541
+
542
+ ### Naming of exposed routes
543
+
544
+ The routes to standalone components are named and you can point to them using Rails' `..._path` and `..._url` helpers. The naming scheme is: `[standalone]_[component]_[family]_comp`. Examples:
545
+
546
+ - Default standalone: `Components::Users::Index` exports `index_users_comp` and thus `index_users_comp_path` can be used.
547
+ - Named standalone: If `standalone :foo, path: ...` is used within `Components::Users::Index`, the exported name is `foo_index_users_comp`.
548
+
549
+ ### Handling formats
550
+
551
+ Compony is capable of responding to formats like Rails does. This is useful to deliver PDFs, CSV files etc. to a user from within Compony. This can be achieved by specifying the `respond` block:
552
+
553
+ ```ruby
554
+ setup do
555
+ standalone path: 'generate/report' do
556
+ verb :get do
557
+ # Respond with a file when generate/report.pdf is GETed:
558
+ respond :pdf do
559
+ file, filename = PdfGenerator.generate(params, current_ability)
560
+ send_data(file, filename:, type: 'application/pdf')
561
+ end
562
+ # If someone visits generate/report, issue a 404:
563
+ respond do
564
+ fail ActionController::RoutingError, 'Unsupported format - please make sure your URL ends with `.pdf`.'
565
+ end
566
+ end
567
+ end
568
+ end
569
+ ```
570
+
571
+ ### Redirect in `respond` or in `before_render`?
572
+
573
+ Rails controller redirects can be issued both in a verb DSL's `respond` block and in `before_render`. The rule of thumb that tells you which way to go is:
574
+
575
+ - If you want to redirect depending on the HTTP verb, use `respond`.
576
+ - If you want to redirect depending on params, state, time etc. **independently of the HTTP verb**, use `before_render`, as this is more convenient than writing a standalone -> verb -> respond tree.
577
+
578
+ ## Inheritance
579
+
580
+ When inheriting from another component class, `setup` can be called in the child as well in order to overwrite specified configurations. The parent's `setup` block will be run first, then the child's, then the grand-child's and so on.
581
+
582
+ Omit any configuration that you want to keep from the parent class. For instance, if your parent's setup looks like this:
583
+
584
+ ```ruby
585
+ setup do
586
+ standalone path: 'foo/bar' do
587
+ layout 'funky'
588
+ verb :get do
589
+ authorize { true }
590
+ end
591
+ end
592
+ content do
593
+ h1 'Test'
594
+ end
595
+ end
596
+ ```
597
+
598
+ Assuming you want to implement a child class that only differs by layout and adds more content below "test", you can implement:
599
+
600
+ ```ruby
601
+ setup do
602
+ standalone do
603
+ layout 'dark'
604
+ end
605
+ add_content do
606
+ para 'This will appear below "Test".'
607
+ end
608
+ end
609
+ ```
610
+
611
+ ### Un-exposing a component
612
+
613
+ If a component's parent class is standalone but the child should not be, use `clear_standalone!`:
614
+
615
+ ```ruby
616
+ setup do
617
+ clear_standalone!
618
+ end
619
+ ```
620
+
621
+ ## Nesting
622
+
623
+ Components can be arbitrarily nested. This means that any component exposing content can instantiate an arbitrary number of sub-components that will be rendered as part of its own content. This results in a component tree. Sub-components are aware of the nesting and even of their position within the parent. The topmost component is called the **root component** and it's the only component that must be standalone. If you instead render the topmost component from a custom view, there is conceptually no root component, but Compony has no way to detect this special case.
624
+
625
+ Nesting is orthogonal to inheritance, they are two entirely different concepts. For disambiguating "parent component", we will make an effort to apply that term to nesting only, while writing "parent component class" if inheritance is meant.
626
+
627
+ Sub-components are particularly useful for DRYing up your code, e.g. when a visual element is used in multiple places of your application or even multiple times on the same page.
628
+
629
+ Nesting occurs when a component is being rendered. It is perfectly feasible to use an otherwise standalone component as a sub-component. Doing so simply plugs it into the content of another component and any arguments can be given to its constructor.
630
+
631
+ Note that only the root component runs authentication and authorization. Thus, be careful which components you nest.
632
+
633
+ To create a sub-component, use `sub_comp` in a component's content block. Any keyword arguments given will be passed to the sub-component. It is strictly recommended to exclusively use `sub_comp` (or its resourceful pendent, see below) to nest components, as this method makes a component aware of its exact nesting.
634
+
635
+ Here is a simple example of a component that displays numbers as binary:
636
+
637
+ ```ruby
638
+ # app/components/numbers/binary.rb
639
+ class Components::Nestings::Binary < Compony::Component
640
+ def initialize(*args, number: nil, **kwargs, &block)
641
+ @number = nil # If this component is initialized with the argument `number`, it will be stored in the component instance.
642
+ end
643
+ setup do
644
+ # standalone and other configs are omitted in this example.
645
+ content do
646
+ # If the initializer did not store `number`, check whether the Rails request contains the parameter `number`:
647
+ # Note: do not do that, as we will demonstrate below.
648
+ @number ||= params[:number].presence&.to_i || 0
649
+ # Display the number as binary
650
+ para "The number #{@number} has the binary form #{@number.to_s(2)}."
651
+ end
652
+ end
653
+ end
654
+ ```
655
+
656
+ If used standalone, the number can be set by using a GET parameter, e.g. `?number=5`. The result is something like this:
657
+
658
+ ```text
659
+ The number 5 has the binary form 101.
660
+ ```
661
+
662
+ Now, let's write a component that displays three different numbers side-by-side:
663
+
664
+ ```ruby
665
+ # app/components/numbers/binary_comparator.rb
666
+ class Components::Nestings::BinaryComparator < Compony::Component
667
+ setup do
668
+ # standalone and other configs are omitted in this example.
669
+ content do
670
+ concat sub_cop(Components::Nestings::Binary, number: 1).render(controller)
671
+ concat sub_cop(Components::Nestings::Binary, number: 2).render(controller)
672
+ concat sub_cop(Components::Nestings::Binary, number: 3).render(controller)
673
+ end
674
+ end
675
+ end
676
+ ```
677
+
678
+ The result is something like this:
679
+
680
+ ```text
681
+ The number 1 has the binary form 1.
682
+ The number 2 has the binary form 10.
683
+ The number 3 has the binary form 11.
684
+ ```
685
+
686
+ However, this is static and no fun. We cannot use the HTTP GET parameter any more because all three `Binary` sub-components listen to the same parameter `number`. To fix this, we will need to scope the parameter using the `param_name` as explained in the next subsection.
687
+
688
+ ### Proper parameter naming for (nested) components
689
+
690
+ As seen in above, even components can be arbitrarily nested, making it harder to identify which HTTP GET parameter in the request is intended for which component. To resolve this, Compony provides nesting-aware scoping of parameter names:
691
+
692
+ - Each component has an `index`, given to it by the `sub_comp` call in the parent, informing it witch n-th child of the parent it is.
693
+ - For instance, in the example above, the three `Binary` components have indices 0, 1 and 2.
694
+ - Each component has an `id` which corresponds to `"#{family_name}_#{comp_name}_#{@index}"`.
695
+ - For instance, the last `Binary` component from the example above has ID `nestings_binary_2`.
696
+ - The `BinaryComparator` has ID `nestings_binary_comparator_0`.
697
+ - Each component has a `path` indicating its exact position in the nesting tree as seen from the root component.
698
+ - In the example above, the last `Binary` component has path `nestings_binary_comparator_0/nestings_binary_2`.
699
+ - `BinaryComparator` has path `nestings_binary_comparator_0`.
700
+ - Each component provides the method `param_name` that takes the name of a parameter name and prepends the first 5 characters of the component's SHA1-hashed path to it.
701
+ - For instance, if `param_name(:number)` is called on the last `Binary` component, the output is `a9f3d_number`.
702
+ - If the same method is called on the first `Binary` component, the output is `f6e86_number`.
703
+
704
+ In short, `param_name` should be used to prefix every parameter that is used in a component that could potentially be nested. It is good practice to apply it to all components. `param_name` has two important properties:
705
+
706
+ - From the param name alone, it is not possible to determine to which component the parameter belongs. However:
707
+ - `param_name` is consistent across reloads of the same URL (given that the components are still the same) and thus each component will be able to identify its own parameters and react to them.
708
+
709
+ With that in mind, let's adjust our `Binary` component. In this example, we will assume that we have implemented yet another component called `NumberChooser` that provides a number input with a Stimulus controller attached. That controller is given the parameter as a String value, such that the it can set the appropriate HTTP GET param and trigger a full page reload to the `BinaryComparator` component.
710
+
711
+ Further, we can drop the custom initializer from the `Binary` component, as the number to display is exclusively coming from the HTTP GET param. The resulting code looks something like:
712
+
713
+ ```ruby
714
+ # app/components/numbers/binary_comparator.rb
715
+ class Components::Nestings::BinaryComparator < Compony::Component
716
+ setup do
717
+ # standalone and other configs are omitted in this example.
718
+ content do
719
+ 3.times do
720
+ concat sub_cop(Components::Nestings::Binary).render(controller)
721
+ end
722
+ end
723
+ end
724
+ end
725
+
726
+ # app/components/numbers/binary.rb
727
+ class Components::Nestings::Binary < Compony::Component
728
+ setup do
729
+ # standalone and other configs are omitted in this example.
730
+ content do
731
+ # This is where we use param_name to retrieve the parameter for this component, regardless whether it's standalone or used as a sub-comp.
732
+ @number ||= params[param_name(:number)].presence&.to_i || 0
733
+ # Display the number as binary
734
+ para "The number #{@number} has the binary form #{@number.to_s(2)}."
735
+ # Display the number input that will reload the page to adjust to the user input. We give it the param_name such that it can set params accordingly.
736
+ concat sub_comp(Components::Nestings::NumberChooser, param_name: param_name(:number))
737
+ end
738
+ end
739
+ end
740
+ ```
741
+
742
+ The result for the URL `path/to/binary_comparator?a9f3d_number=2&e70b4_number=4&a9f3d_number=8` is something like this:
743
+
744
+ ```text
745
+ The number 2 has the binary form 10. Enter a number and press ENTER: [2]
746
+ The number 4 has the binary form 100. Enter a number and press ENTER: [4]
747
+ The number 8 has the binary form 1000. Enter a number and press ENTER: [8]
748
+ ```
749
+
750
+ Note that this example is completely stateless, as all the info is encoded in the URL.
751
+
752
+ ## Resourceful components
753
+
754
+ So far, we have mainly seen how to present static content, without considering how loading and storing data is handled. Whenever a component is about data, be it a collection (e.g. index, list) or a single instance (e.g. new, show, edit, destroy, form), that component typically becomes resourceful. In order to implement a resourceful component, include the mixin `Compony::ComponentMixins::Resourceful`.
755
+
756
+ Resourceful components use an instance variable `@data` and provide a reader `data` for it. As a convention, always store the data the component "is about" in this variable.
757
+
758
+ Further, the class of which `data` should be can be specified and retrieved by using `data_class`. By default, `data_class` is inferred from the component's family name, i.e. `Components::User::Show` will automatically return `User` as `data_class`.
759
+
760
+ The mixin adds extra hooks that can be used to store logic that can be executed in the request context when the component is rendered standalone. The formulation of that sentence is important, as the decision which of these blocks are executed depends on the verb DSL. But before elaborating on that, let's first look at all the available hooks provided by the Resourceful mixin:
761
+
762
+ - `load_data`: Important. Specify a block that assigns something to `@data` here. The block will be run before authorization - thus, you can check `@data` for authorizing (e.g. `can?(:read, @data)`).
763
+ - `after_load_data`: Optional. If a block is specified, it is run immediately after `load_data`. This is useful if you inherit from a component that loads data but you need to alter something, e.g. refining a collection.
764
+ - `assign_attributes`: Important for components that alter data, e.g. New, Edit. Specify a block that assigns attributes to your model from `load_data`. The model is now dirty, which is important: **do not save your model here**, as authorization has not yet been performed. Also, **do not forget to validate params before assigning them to attributes**.
765
+ - `after_assign_attributes`: Optional. If a block is specified, it is run immediately after `assign_attributes`. Its usage is similar to that of `after_load_data`.
766
+ - (At this point, your `authorize` block is executed, throwing a `CanCan::AccessDenied` exception causing HTTP 403 not authorized if the block returns false.)
767
+ - `store_data`: Important for components that alter data, e.g. New, Edit. This is where you save your model stored in `@data` to the database.
768
+
769
+ Another important aspect of the Resourceful mixin is that it also **extends the Verb DSL** available in the component. The added calls are:
770
+
771
+ - `load_data`
772
+ - `assign_attributes`
773
+ - `store_data`
774
+
775
+ Unlike the calls above, which are global for the entire component, the ones in the Verb DSL are on a per-verb basis, same as the `authorize` call. If the same hook is both given as a global hook and in the Verb DSL, the Verb DSL hook overwrites the global one. The rule of thumb on where to place logic is:
776
+
777
+ - If multiple verbs use the same logic for a hook, place it in the global hook. For example, let us consider an Edit component: if GET is called on it, the model is loaded and parameters are assigned to it in order to fill the form's inputs. If PATCH is called, the exact same thing is done before attempting to save the model. In this case, you would implement both `load_data` and `assign_attributes` as global hooks.
778
+ - If a hook is specific to a single verb, place it in the verb config.
779
+
780
+ Let's build an example of a simplified Destroy component. In practice, you'd instead inherit from `Compony::Components::Destroy`. However, for the sake of demonstration, we will implement it from scratch:
781
+
782
+ ```ruby
783
+ class Components::Users::Destroy < Compony::Component
784
+ # Make the component resourceful
785
+ include Compony::ComponentMixins::Resourceful
786
+
787
+ setup do
788
+ # Let the path be of the form users/42/destroy
789
+ standalone path: 'users/:id/destroy' do
790
+ verb :get do
791
+ # In the case of a GET request, ask for confirmation, not deleting anything.
792
+ # Nevertheless, we should authorize :destroy, not :read.
793
+ # Reason: this way, buttons pointing to this component will not be shown
794
+ # to users which lack the permission to destroy @data.
795
+ authorize { can?(:destroy, @data) }
796
+ end
797
+
798
+ verb :delete do
799
+ # In the case of a DELETE request, the record will be destroyed.
800
+ authorize { can?(:destroy, @data) }
801
+ store_data { @data.destroy! }
802
+ # We overwrite the respond block because we want to redirect, not render
803
+ respond do
804
+ flash.notice = "#{@data.label} was deleted."
805
+ redirect_to Compony.path(:index, :users)
806
+ end
807
+ end
808
+ end
809
+
810
+ # Resourceful components have a default `load_data` block that loads the model.
811
+ # Therefore, the default behavior is already set to:
812
+ # load_data { @data = User.find(params[:id]) }
813
+
814
+ label(:short) { |_| 'Delete' }
815
+ label(:long) { |data| "Delete #{data.label}" }
816
+ content do
817
+ h1 "Are you sure to delete #{@data.label}?"
818
+ div compony_button(:destroy, @data, label: 'Yes, delete', method: :delete)
819
+ end
820
+ end
821
+ end
822
+ ```
823
+
824
+ ### Complete resourceful lifecycle
825
+
826
+ This graph documents a typical resourceful lifecycle according to which Compony's pre-built components (see below) are implemented.
827
+
828
+ - `load_data` creates or fetches the resource from the database.
829
+ - `after_load_data` can refine the resource, e.g. add scopes to a relation.
830
+ - `assign_attributes` takes the HTTP parameters, validates them and assigns them to the resource.
831
+ - `after_assign_attributes` can refine the assigned resource, e.g. provide defaults for blank attributes.
832
+ - `authorize` is called.
833
+ - `store_data` creates/updates/destroys the resource.
834
+ - `respond` typically shows a flash and redirects to another component.
835
+
836
+ ![Graph of the complete resourceful lifecycle](doc/resourceful_lifecycle.png)
837
+
838
+ ### Nesting resourceful components
839
+
840
+ As mentioned earlier, hooks such as those provided by Resourceful typically run only when a component is accessed standalone. This means that in a nested setting, only the component running those hooks is the root component.
841
+
842
+ When nesting resourceful components, it is therefore best to load all necessary data in the root component. Make sure to include any relations used by sub-components in order to avoid "n+1" queries in the database.
843
+
844
+ `resourceful_sub_comp` is the resourceful sibling of `sub_comp` and both are used the same way. Under the hood, the resourceful call passes two extra parameters to the sub component: `data` and `data_class`.
845
+
846
+ The rule of thumb thus becomes:
847
+
848
+ - When a resourceful component instantiates a resourceful sub-component, use `resourceful_sub_comp` in the parent component.
849
+ - When a resourceful component instantiates a non-resourceful sub-component, use `sub_comp`.
850
+ - The situation where a non-resourceful component instantiates a resourceful component should not occur. Instead, make your parent component resourceful, even if it doesn't use the data itself. By housing a resourceful sub-comp, the parent component's nature inherently becomes resourceful and you should use the Resourceful mixin.
851
+
852
+ ## Compony helpers, links and buttons
853
+
854
+ When pointing to or instantiating a component, writing the whole class name would be cumbersome. For this reason, Compony has several helpers that will retrieve the correct class for you. The most important ones are explained in this subsection. The terms are defined as follows:
855
+
856
+ - Component name or constant: For a component `Components::Users::Show`, this would be `'Show'`, `'show'`, or `:show`
857
+ - Family name or constant: For a component `Components::Users::Show`, this would be `'Users'`, `'users'`, or `:users`
858
+ - Model: an instance of a class that implements the `model_name` method in the same way as `ActiveRecord::Base` does. For helpers that support giving models, Compony will use `model_name` to auto-infer the family name. This requires you to name the component according to convention, i.e. the family name must match the model's pluralized camelized `model_name`.
859
+
860
+ ### Getting the class of a component
861
+
862
+ - `Compony.comp_class_for(comp_name_or_cst, model_or_family_name_or_cst)` returns the class or nil if not found.
863
+ - `Compony.comp_class_for!(comp_name_or_cst, model_or_family_name_or_cst)` returns the class. If the class is not found, an error will be raised.
864
+
865
+ Example:
866
+
867
+ ```ruby
868
+ my_component = Compony.comp_class_for!(:show, User.first).new
869
+ my_component.class # Components::Users::Show
870
+ ```
871
+
872
+ #### Getting a path to a component
873
+
874
+ - `Compony.path(comp_name_or_cst, model_or_family_name_or_cst)` returns the route to a component. Additional positional and keyword arguments will be passed to the Rails helper.
875
+
876
+ If a model is given, its ID will automatically be added as the `id` parameter when generating the route. This means:
877
+
878
+ - To generate a path to a non-resourceful component, pass the family name.
879
+ - To generate a path to a resourceful component, prefer passing an instance instead of a family name.
880
+
881
+ Examples:
882
+
883
+ ```ruby
884
+ link_to 'User overview', Compony.path(:index, :users) # -> 'users/index'
885
+ link_to 'See user page', Compony.path(:show, User.first) # -> 'users/show/1'
886
+ link_to 'See user page', Compony.path(:show, :users, id: 1) # -> 'users/show/1'
887
+ ```
888
+
889
+ Note that the generated paths in the example are just for illustration purposes. The paths point to whatever path you configure in the target component's default standalone config. Also, this example is not how you should generate links to components, as is explained in the next subsection.
890
+
891
+ ### Generating a link to a component
892
+
893
+ In order to allow a user to visit another component, don't implement your links and buttons manually. Instead, use Compony's links and buttons, as those extract information from the target component, avoiding redundant code and making refactoring much easier.
894
+
895
+ Compony comes with the view helper `compony_link` that is available in any of your views, including a component's `content` blocks. The link's label is inferred from the component the link points to. `compony_link` is used as follows:
896
+
897
+ - To generate a link to a non-resourceful component, pass the family name.
898
+ - To generate a link to a resourceful component, prefer passing an instance instead of a family name. More precisely, you must pass an instance if the component's label requires an argument.
899
+
900
+ Any additional arguments passed to `compony_link` will be given to Rails' `link_to` method, allowing you to set parameters, HTTP method, terget, rel etc.
901
+
902
+ Examples:
903
+
904
+ ```ruby
905
+ compony_link(:index, :users) # "View all users" -> 'users/index'
906
+ compony_link(:index, :users, label_opts: { format: :short }) # "All" -> 'users/index'
907
+ compony_link(:show, User.first) # "View John Doe" -> 'users/show/1'
908
+ compony_link(:destroy, User.first, method: :delete) # "Delete John Doe" -> 'users/destroy/1'
909
+
910
+ # NOT working:
911
+ compony_link(:show, :users, id: 1) # Error: The label for the Users::Show component takes an argument which was not provided (the user's label)
912
+ ```
913
+
914
+ ### Generating a button to a component
915
+
916
+ Compony buttons are components that render a button to another component. While the view helper `compony_button` works similar to `compony_link`, you can also manually instantiate a button and work with it like with any other component.
917
+
918
+ Similar to links, Compony buttons take a component name and either a family or model. The label, path, method and title (i.e. tooltip) can be overwritten by passing the respective arguments as shown below.
919
+
920
+ Compony buttons have a type that is either `:button` or `:submit`. While the first works like a link redirecting the user elsewhere, the second is used for submitting forms. It can be used inside a `form_for` or `simple_form_for`.
921
+
922
+ A compony button figures out on it's own whether it's clickable or not:
923
+
924
+ - Buttons can be disabled explicitly by passing `enabled: false` as a parameter.
925
+ - If a user is not authorized to access the component a button is pointing to, the button is not displayed.
926
+ - If the target component should not be accessible due to a prevention in the feasibility framework (explained later), the button is disabled and a tooltip is shown explaining why the button is not clickable.
927
+
928
+ Do not directly instantiate `Compony::Components::Button`. Instead, use `Compony.button`:
929
+
930
+ ```ruby
931
+ my_button = Compony.button(:index, :users) # "View all users" -> 'users/index'
932
+ my_button = Compony.button(:index, :users, label_opts: { format: :short }) # "All" -> 'users/index'
933
+ my_button = Compony.button(:index, :users, label: 'Back') # "Back" -> 'users/index'
934
+ my_button = Compony.button(:show, User.first) # "View John Doe" -> 'users/show/1'
935
+ my_button = Compony.button(:new, :users, label: 'New customer', params: { user: { type: 'customer' } }) # "New customer" -> 'users/new?user[type]=customer'
936
+ my_button = Compony.button(:new, :users, label: 'New customer', params: { user: { type: 'customer' } }, method: :post) # Instantly creates user.
937
+ my_button = Compony.button(label: 'I point to a plain Rails route', path: 'some/path') # Specifying a custom path
938
+ my_button = Compony.button(label: 'Nothing happens if you click me') # javascript:void()
939
+ my_button = Compony.button(label: 'Not implemented yet', enabled: false) # Disabled button
940
+
941
+ # `enabled` and `path` can also be provided with a callable (block or lambda) to defer evaluation until when the button is rendered.
942
+ # The lambdas will be called in the button's `before_render` and given the controller, allowing you to query request specific data.
943
+ my_button = Compony.button(label: 'I point to a plain Rails route', path: ->{ |controller| controller.helpers.some_rails_path })
944
+ my_button = Compony.button(:index, :users, enabled: -> { |controller| controller.current_ability.can?(:read, :index_pages) })
945
+ ```
946
+
947
+ A Compony button can be rendered like any other component:
948
+
949
+ ```erb
950
+ <%= my_button.render(controller) %>
951
+ ```
952
+
953
+ However, it is much easier to just use the appropriate view helper instead, which takes the same arguments as `Compony.button`:
954
+
955
+ ```ruby
956
+ compony_button(:index, :users)
957
+ ```
958
+
959
+ If you need to render many buttons that share a parameter, the call `Compony.with_button_defaults` allows you to DRY up your code:
960
+
961
+ ```ruby
962
+ # Assuming this is inside a Dyny view context and each button should be inside a div.
963
+ # Without with_button_defaults:
964
+ div compony_button(:new, :documents, label_opts: { format: :short }, method: :post)
965
+ div compony_button(:new, :letters, label_opts: { format: :short }, method: :post)
966
+ div compony_button(:new, :articles, label_opts: { format: :short }, method: :post)
967
+
968
+ # Equivalent using with_button_defaults:
969
+ Compony.with_button_defaults(label_opts: { format: :short }, method: :post) do
970
+ div compony_button(:new, :documents)
971
+ div compony_button(:new, :letters)
972
+ div compony_button(:new, :articles)
973
+ end
974
+ ```
975
+
976
+ #### Implementing custom buttons
977
+
978
+ Plain HTML buttons are not exactly eye candy, so you will likely want to implement your button kind with black jack and icons. For this reason, the button instantiated by Compony's button helpers can be customized.
979
+
980
+ To build your own button class, inherit as follows:
981
+
982
+ ```ruby
983
+ class MyButton < Compony::Components::Button
984
+ def initialize(*args, **kwargs, &block) # Add extra arguments here
985
+ super(*args, **kwargs, &block)
986
+ # Add extra initialization code here
987
+ end
988
+
989
+ # Add/replace before_render/content here. Be careful to not overwrite code you depend on. Check Compony's button's code for details.
990
+ end
991
+ ```
992
+
993
+ Then, in the Compony initializer, register your custom button class to have Compony instantiate it whenever `Compony.button` or another helper is called:
994
+
995
+ ```ruby
996
+ # config/initializers/compony.rb
997
+ Compony.button_component_class = 'MyButton'
998
+ ```
999
+
1000
+ ## Actions
1001
+
1002
+ The word "actions" is heavily overused, so here is a disambiguation:
1003
+
1004
+ - Rails controller actions: a method that is implemented in a Rails controller
1005
+ - CanCanCan actions: the first method to CanCanCan's `can?` method
1006
+ - Compony actions: buttons that point to other components
1007
+
1008
+ At this point, Compony actions are a loose concept, which will likely be refined in the future. Currently, Compony actions are defined as buttons that point to other components. These buttons can be disabled by the prevention framework (explained below).
1009
+
1010
+ ### Defining and manipulating root actions
1011
+
1012
+ In addition to regular buttons that are rendered as part of the content blocks, components can expose root actions with the `actions` call. Root actions will only be rendered if the component they are defined in is currently the root component.
1013
+
1014
+ To have a component expose a root action, call the method `action` in a `setup` block and return a Compony button:
1015
+
1016
+ ```ruby
1017
+ setup do
1018
+ action :edit do
1019
+ Compony.button(:edit, @data)
1020
+ end
1021
+
1022
+ action :destroy do
1023
+ Compony.button(:destroy, @data)
1024
+ end
1025
+ end
1026
+ ```
1027
+
1028
+ The name of the action ("back" in the example above) allows you to refer to that action in a component inheriting from this one:
1029
+
1030
+ ```ruby
1031
+ # Assuming that this component inherits from the example above
1032
+ setup do
1033
+ skip_action :destroy
1034
+
1035
+ action :overview, before: :edit do
1036
+ Compony.button(:index, :users, label: 'Overview')
1037
+ end
1038
+ end
1039
+ ```
1040
+
1041
+ In this example, two actions will be shown: overview and edit.
1042
+
1043
+ An action button can be disabled through the prevention framework (explained below). However, it can also instead be hidden completely by returning nil from within the action block:
1044
+
1045
+ ```ruby
1046
+ action :edit do
1047
+ next if @data.locked?
1048
+ Compony.button(:edit, @data)
1049
+ end
1050
+ ```
1051
+
1052
+ The action in this example will be skipped entirely if `locked?` returns true.
1053
+
1054
+ ### Displaying root actions
1055
+
1056
+ Root actions are not shown by default in Compony because layouting is up to you. In order to display the root component's actions, add the following view helper call to your layout:
1057
+
1058
+ ```erb
1059
+ <%# layouts/application.html.erb %>
1060
+ ...
1061
+ <%= compony_actions %>
1062
+ ```
1063
+
1064
+ If there is currently no root component, or if the root component defines no actions, this does nothing. However, if there are root actions available, the Compony buttons returned by the root component will be rendered.
1065
+
1066
+ ## The feasibility framework
1067
+
1068
+ When a user has the permission to perform an action in general, but it is currently not feasible (for instance if the concerned object is incomplete, or if right now is not the right time to do the action), buttons pointing to that action should be disabled and a HTML `title` attribute should cause a tooltip explaining why this action cannot be performed right now.
1069
+
1070
+ This can be easily achieved with the feasibility framework, which allows you to prevent actions on conditions, along with an error message. Formulate the error message similar to Rails validation errors (first letter not capital, no period at the end), as the prevention framework is able to concatenate multiple error messages if multiple conditions prevent an action.
1071
+
1072
+ The feasibility framework currently only makes sense for resourceful components.
1073
+
1074
+ Example:
1075
+
1076
+ ```ruby
1077
+ # app/models/user.rb
1078
+ # Prevent sending an e-mail to a user that has no e-mail address present
1079
+ prevent :send_mail, 'the e-mail address is missing' do
1080
+ email.blank?
1081
+ end
1082
+
1083
+ # app/models/event.rb
1084
+ # Multiple actions can be prevented at once:
1085
+ # Prevent creating or removing a booking to an event that lies in the past or that is locked
1086
+ prevent [:create_booking, :destroy_booking], 'the event is already over' do
1087
+ ends_at < Time.zone.now || locked?
1088
+ end
1089
+ ```
1090
+
1091
+ **Note that the feasibility framework currently only affects buttons pointing to actions, not the action itself.** If a user were to issue the HTTP call manually, the component happily responds and performs the action. This is why you should always back important preventions with an appropriate Rails model validation:
1092
+
1093
+ - The Rails model validation prevents that invalid data can be saved to the database.
1094
+ - The feasibility framework disables buttons and explains to guide the user.
1095
+ - Authorization is orthogonal to this, limiting the actions of a specific user.
1096
+ - If an action is both prevented and not authorized, the authorization "wins" and the action button is not shown at all.
1097
+
1098
+ Compony has a feature that auto-detects feasibility. In particular, it checks for `dependent` relations in the `has_one`/`has_many` relations and disables delete buttons that point to objects that have dependent objects that cannot automatically be destroyed.
1099
+
1100
+ To disable auto detection, call `skip_autodetect_feasibilities` in your model.
1101
+
1102
+ ## Ownership
1103
+
1104
+ Ownership is a concept that captures the nature of data to be presented by Compony. It means that an object only makes sense within the context of another that it belongs to. Owned objects have therefore no index component, because they don't have meaning on their own. For instance:
1105
+
1106
+ - typically NOT owned: visitors and vouchers: while a voucher can `belong_to` a visitor, the voucher can be managed on it's own. Vouchers can have their own index page which makes it possible to search for a given voucher code across all vouchers.
1107
+ - typically owned: users and their permissions: a permission only makes sense with respect to its associated user and having a list of all permissions across the system would rarely be a use case. In this case, we consider the `Permission` model to be conceptually **owned by** the `User` model.
1108
+
1109
+ In Compony, if a model class is owned by another, it means that:
1110
+
1111
+ - The owned model has a non-optional `belongs_to` relation ship to its owner.
1112
+ - The owned model class has no Index component.
1113
+ - Pre-built components (more on them later) offer root actions to the owner model and redirect to its Show component instead of to the current object's Index component.
1114
+
1115
+ To mark a model as owned by another, write the following code **in the model**:
1116
+
1117
+ ```ruby
1118
+ # app/models/permission.rb
1119
+ owned_by :user
1120
+ ```
1121
+
1122
+ ## Fields
1123
+
1124
+ Compony fields are your models' attributes that you wish to expose in your application's UI. They are a central place to store important information about those attributes, accessible from everywhere and without the need for a database connection.
1125
+
1126
+ Every Compony field must define at least a name and type. Compony types and ActiveRecord types are similar but not equivalent. While ActiveRecord uses types for storing data in the DB, Compony fields use them for presenting it. For instance, the Compony "string" type covers any kind of string, including ActiveRecord's "string", "text" etc. Similarly, Compony has no "numeric" type - use "integer" or "decimal" instead, depending on whether or not you want to show decimals or not. There are additional field types like "color", "url" etc. You can find a complete list of all Compony field types in the module `Compony::ModelFields`.
1127
+
1128
+ Compony fields support Postgres arrays (non-nested).
1129
+
1130
+ A particularly interesting model field is `Association` which handles `belongs_to`, `has_many` and `has_one` associations, automatically resolving the association's nature and providing links to the appropriate component.
1131
+
1132
+ Every Compony field can further take an arbitrary amount of additional named arguments. Those can be retrieved by calling `YourRailsModel.fields[:field_name].extra_attrs`.
1133
+
1134
+
1135
+ Here is an example call to fields for a User model:
1136
+
1137
+ ```ruby
1138
+ # app/models/user.rb
1139
+ class User < ApplicationRecord
1140
+ field :first_name, :string
1141
+ field :last_name, :string
1142
+ field :user_role, :anchormodel
1143
+ field :website, :url
1144
+ field :created_at, :datetime
1145
+ field :updated_at, :datetime
1146
+ end
1147
+ ```
1148
+
1149
+ Compony fields provide the following features:
1150
+
1151
+ - a label that lets you generate a name for the column: `User.fields[:first_name].label`
1152
+ - `value_for`: given a model instance, formats the data (e.g. a field of type "url" will produce a link).
1153
+ - Features for forms:
1154
+ - `simpleform_input` auto-generates in input for a simple form (from the `simple_form` gem).
1155
+ - `simpleform_input_hidden` auto-generates a hidden input.
1156
+ - `schema_line` auto-generates a DSL call for Schemacop v3 (from the `schemacop` gem), which is useful for parameter validation.
1157
+
1158
+ You can then use these fields in other components, for instance a list as described in the example at the top of this guide:
1159
+
1160
+ ```ruby
1161
+ User.fields.values.each do |field|
1162
+ span do
1163
+ concat "#{field.label}: #{field.value_for(user)} " # Display the field's label and apply it to value
1164
+ end
1165
+ end
1166
+ ```
1167
+
1168
+ ### Implementing your own fields
1169
+
1170
+ You can implement your own model fields. Make sure they are all within the same namespace and inherit at least from `Compony::ModelFields::Base`. To enable them, write an initializer that overwrites the array `Compony.model_field_namespaces`. Namespaces listed in the array are prioritized from first to last. If a field (e.g. `String`) exists in multiple declared namespaces, the first will be used. This allows you to overwrite Compony fields.
1171
+
1172
+ Example:
1173
+
1174
+ ```ruby
1175
+ # config/initializers/compony.rb
1176
+ Compony.model_field_namespaces = ['MyCustomModelFields', 'Compony::ModelFields']
1177
+ ```
1178
+
1179
+ You can then implement `MyCustomModelFields::Animal`, `MyCustomModelFields::String` etc. You can then use `field :fav_animal, :animal` in your model.
1180
+
1181
+ ## Pre-built components shipped with Compony
1182
+
1183
+ Compony comes with a few pre-built components that cover the most common cases that can be speed up development. They are meant to be inherited from and the easiest way to do this is by using the Rails generator `rails new component` (described below).
1184
+
1185
+ The pre-built components can be found in the module `Compony::Components`. As you can see, there is no Show and no Index component. The reason is that these will depend a lot on your application's UI framework (e.g. Bootstrap) and thus the benefits a UI-agnostic base component can provide are minimal. Additionally, these components are very easy to implement, as is illustrated in the example at the beginning of this documentation.
1186
+
1187
+ In the following, the pre-built components currently shipped with Compony are presented.
1188
+
1189
+ ### Button
1190
+
1191
+ As stated earlier, buttons are just regular components that rendered in-place. They don't make use of nesting logic (and presumably never will), and thus they are rendered as-is, without `sub_comp`.
1192
+
1193
+ You will rarely (or probably never) instantiate a button on your own, but use helpers like `Compony.button` or `compony_button`. For this reason, the documentation for instantiating buttons is located in the section documenting those helpers above.
1194
+
1195
+ ### Destroy
1196
+
1197
+ This component is the Compony equivalent to a typical Rails controller's `destroy` action.
1198
+
1199
+ `Compony::Components::Destroy` is a resourceful standalone component that listens to two verbs:
1200
+
1201
+ - GET will cause the Destroy component to ask if the resource should be destroyed, along with a button pointing to the DELETE verb. If the record does not exist, a HTTP 404 code is returned.
1202
+ - DELETE will `destroy!` the resource, show a flash and redirect to:
1203
+ - if present: the data's Show component
1204
+ - otherwise: the data's Index component
1205
+
1206
+ Authorization checks for `destroy` even in GET. The reason is that users that aren't able to destroy a resource shouldn't even arrive at the page asking them whether they want to do so, unable to click the only button due to lacking permissions. This also causes any `compony_link` and `compony_button` to Destroy components to be hidden if the user is unable to destroy the corresponding resource.
1207
+
1208
+ This component largely follows the resourceful lifecycle, explained in above under "Resourceful". As can be expected, the resource is loaded by `Resourceful`'s default load block and `store_data` is implemented to destroy the resource.
1209
+
1210
+ If the resource is owned (see "Ownership" documentation above), the component provides a `:back_to_owner` root action in the form of a cancel button.
1211
+
1212
+ The following DSL methods are implemented to allow for convenient overrides of default logic:
1213
+
1214
+ - The block `on_destroyed` is evaluated between successful record destruction and responding. By default, it is not implemented and doing so is optional. This would be a suitable location for hooks that update state after a resource was destroyed (like an `after_destroy` hook, but only executed if a record was destroyed by this component). Do not redirect or render here, use the next blocks instead.
1215
+ - The block given in `on_destroyed_respond` is evaluated after destruction and by default shows a flash, then redirects. The redirection is performed with HTTP code 303 ("see other") in oder to force a GET request. This is required for the component to work with Turbo. Overwrite this block if you need to completely customize all logic that happens after destruction. If this block is overwritten, `on_destroyed_redirect_path` will not be called.
1216
+ - `on_destroyed_redirect_path` is evaluated as the second step of `on_destroyed_respond` and redirects to the resource's Show or Index component as described above. Overwrite this block in order to redirect to another component instead, while keeping the default flash provided by `on_destroyed_respond`.
1217
+
1218
+ ### WithForm
1219
+
1220
+ `Compony::Components::WithForm` is an abstract base class for components that render a form. Those components can further be resourceful, but don't have to be. If a component inherits from WithForm, it is always twinned with another component that will provide the form.
1221
+
1222
+ WithForm adds the following DSL methods:
1223
+
1224
+ - `form_comp_class` sets the class that will be instantiated by `form_comp`
1225
+ - `form_comp` returns an instance of the Form component twinned with this component. If `form_comp_class` was never set, it will default to loading the component named `Form` in the same family as this component.
1226
+ - `submit_verb` takes a symbol containing a verb, e.g. `:patch`. It defines this component's standalone verb that should be called when the twinned Form component is submitted.
1227
+ - `submit_path` defaults to this component's standalone path. You can override this to submit the form to another component, should you need it.
1228
+
1229
+ ### Form
1230
+
1231
+ This component holds a form and should only be instantiated by the `form_comp` call of a component that inherits from WithForm.
1232
+
1233
+ `Compony::Components::Form` is an abstract base class for any components presenting a regular form. This class comes with a lot of tooling for rendering forms and inputs, as well as validating parameters. When the component is rendered, the Gem SimpleForm is used to create the actual form: [https://github.com/heartcombo/simple_form](https://github.com/heartcombo/simple_form).
1234
+
1235
+ Parameters are structured like typical Rails forms. For instance, if you have a form for a `User` model and the attribute is `first_name`, the parameter looks like `user[first_name]=Tom`. In this case, we will call `user` the `schema_wrapper_key`. Parameters are validated using Schemacop: [https://github.com/sitrox/schemacop](https://github.com/sitrox/schemacop).
1236
+
1237
+ The following DSL calls are provided by the Form component:
1238
+
1239
+ - Required: `form_fields` takes a block that renders the inputs of your form. More on that below.
1240
+ - Optional: `skip_autofocus` will prevent the first input to be auto-focussed when the user visits the form.
1241
+ - Typically required: `schema_fields` takes the names of fields as a whitelist for strong parameters. Together with model fields, this will completely auto-generate a Schemacop schema suitable for validating this form. If your argument list gets too long, you can use multiple calls to `schema_field` instead to declare your fields one by one on separate lines.
1242
+ - Optional: `schema_line` takes a single Schemacop line. Use this for custom whitelisting of an argument, e.g. if you have an input that does not have a corresponding model field.
1243
+ - Optional: `schema` allows you to instead fully define your own custom Schemacop V3 schema manually. Note that this disables all of the above schema calls.
1244
+
1245
+ The `form_fields` block acts much like a content block and you will use Dyny there. Two additional methods are made available exclusively inside the block:
1246
+
1247
+ - `field` (not to be confused with the model mixin's static method) takes the name of a model field and auto-generates a suitable SimpleForm input as defined in the field's type.
1248
+ - `f` gives you direct access to the `simple_form` instance. You can use it to write e.g. `f.input(...)`.
1249
+
1250
+ Here is a simple example for a form for a sample user:
1251
+
1252
+ ```ruby
1253
+ class Components::Users::Form < Compony::Components::Form
1254
+ setup do
1255
+ form_fields do
1256
+ concat field(:first_name)
1257
+ concat field(:last_name)
1258
+ concat field(:age)
1259
+ concat field(:comment)
1260
+ concat field(:role)
1261
+ end
1262
+ schema_fields :first_name, :last_name, :age, :comment, :role
1263
+ end
1264
+ end
1265
+ ```
1266
+
1267
+ Note that the inputs and schema are two completely different concepts that are not auto-inferred from each other. You must make sure that they always correspond. If you forget to mention a field in `schema_fields`, posting the form will fail. Luckily, Schemacop's excellent error messaging will explain which parameter is prohibited.
1268
+
1269
+ ### New
1270
+
1271
+ This component is the Compony equivalent to a typical Rails controller's `new` and `create` actions.
1272
+
1273
+ `Compony::Components::New` is a resourceful standalone component based on WithForm that listens to two verbs:
1274
+
1275
+ - GET will cause the New component to create a fresh instance of its `data_class` and render the form.
1276
+ - POST (equivalent to a `create` action in a controller) will attempt to save the resource. If that fails, the form is rendered again with a HTTP 422 code ("unprocessable entity"). If the creation succeeds, a flash is shown and the user is redirected:
1277
+ - if present: the data's Show component
1278
+ - otherwise, if the resource is owned by another resource class: the owner's Show component
1279
+ - otherwise, the data's Index component
1280
+
1281
+ Authorization checks for `create` even in GET. The reason is that it makes no sense to present an empty form to a user who cannot create a new record. This also causes any `compony_link` and `compony_button` to New components to be hidden to users lacking the permission.
1282
+
1283
+ This component follows the resourceful lifecycle, explained in above under "Resourceful". `load_data` is set to create a new record and `store_data` attempts to create it. Parameters are validated in `assign_attributes` using a Schemacop schema that is generated from the form. The schema corresponds to Rail's typical strong parameter structure for forms. For example, a user's New component would look for a parameter `user` holding a hash of attributes (e.g. `user[first_name]=Tom`).
1284
+
1285
+ In case you overwrite `store_data`, make sure to set `@created_succeeded` to true if storing was successful (and to set it to false otherwise).
1286
+
1287
+ The following DSL calls are implemented to allow for convenient overrides of default logic:
1288
+
1289
+ - The block `on_create_failed_respond` is run if `@create_succeeded` is not true. By default, it logs all error messages with level `warn` and renders the component again through HTTP 422, causing Turbo to correctly display the page. Error messages are displayed by the form inputs.
1290
+ - The block `on_created` is evaluated between successful record creation and responding. By default, it is not implemented and doing so is optional. This would be a suitable location for hooks that update state after a resource was created (like an `after_create` hook, but only executed if a record was created by this component). Do not redirect or render here, use the next blocks instead.
1291
+ - The block given in `on_created_respond` is evaluated after successful creation and by default shows a flash, then redirects. Overwrite this block if you need to completely customize all logic that happens after creation. If this block is overwritten, `on_created_redirect_path` will not be called.
1292
+ - `on_created_redirect_path` is evaluated as the second step of `on_created_respond` and redirects to the resource's Show, its owner's Show, or its own Index component as described above. Overwrite this block in order to redirect ot another component instead, while keeping the default flash provided by `on_created_respond`.
1293
+
1294
+ ### Edit
1295
+
1296
+ This component is the Compony equivalent to a typical Rails controller's `edit` and `update` actions.
1297
+
1298
+ `Compony::Components::Edit` is a resourceful standalone component based on WithForm that listens to two verbs:
1299
+
1300
+ - GET will cause the Edit component to load a record given by ID and render the form based on that record. If the record does not exist, a HTTP 404 code is returned.
1301
+ - PATCH (equivalent to a `update` action in a controller) will attempt to save the resource. If that fails, the form is rendered again with a HTTP 422 code ("unprocessable entity"). If the update succeeds, a flash is shown and the user is redirected:
1302
+ - if present: the data's Show component
1303
+ - otherwise, if the resource is owned by another resource class: the owner's Show component
1304
+ - otherwise, the data's Index component
1305
+
1306
+ Unlike in New and Destroy, Edit's authorization checks for `edit` in GET and for `update` in PATCH. This enables you to "abuse" an Edit component to double as a Show component. Users having only `:read` permission will not see any links or buttons pointing to an Edit component. Users having only `:edit` permissions can see the form (including the data) but not submit it. Users having `:write` permissions can edit and update the Resource, in accordance to CanCanCan's `:write` alias.
1307
+
1308
+ This component follows the resourceful lifecycle, explained in above under "Resourceful". Parameters are validated in `assign_attributes` using a Schemacop schema that is generated from the form. The schema corresponds to Rail's typical strong parameter structure for forms. For example, a user's Edit component would look for a parameter `user` holding a hash of attributes (e.g. `user[first_name]=Tom`).
1309
+
1310
+ In case you overwrite `store_data`, make sure to set `@update_succeeded` to true if storing was successful (and to set it to false otherwise).
1311
+
1312
+ The following DSL calls are implemented to allow for convenient overrides of default logic:
1313
+
1314
+ - The block `on_update_failed_respond` is run if `@update_succeeded` is not true. By default, it logs all error messages with level `warn` and renders the component again through HTTP 422, causing Turbo to correctly display the page. Error messages are displayed by the form inputs.
1315
+ - The block `on_updated` is evaluated between successful record creation and responding. By default, it is not implemented and doing so is optional. This would be a suitable location for hooks that update state after a resource was updated (like an `after_update` hook, but only executed if a record was updated by this component). Do not redirect or render here, use the next blocks instead.
1316
+ - The block given in `on_updated_respond` is evaluated after successful creation and by default shows a flash, then redirects. Overwrite this block if you need to completely customize all logic that happens after creation. If this block is overwritten, `on_updated_redirect_path` will not be called.
1317
+ - `on_updated_redirect_path` is evaluated as the second step of `on_updated_respond` and redirects to the resource's Show, its owner's Show, or its own Index component as described above. Overwrite this block in order to redirect ot another component instead, while keeping the default flash provided by `on_updated_respond`.
1318
+
1319
+ ## Generators
1320
+
1321
+ To make your life easier and coding faster, Compony comes with two generators:
1322
+
1323
+ - `rails g component Users::New` will create `app/components/users/new.rb` and, since the component's name coincides with a a pre-built component, automatically inherit from that. If the name is unknown, the generated component will inherit form `Compony::Component` instead. The generator also equips generated components with the boilerplate code that wil be required to make the component work.
1324
+ - The generator can also be called via its alternative form `rails g component users/new`.
1325
+ - `rails g components Users` will generate a set of the most used components.
1326
+
1327
+ ## Internal datastructures
1328
+
1329
+ Compony has a few internal data structures that are worth mentioning. Especially when building your own UI framework on top of Compony, these might come in handy.
1330
+
1331
+ ### MethodAccessibleHash
1332
+
1333
+ This is a simpler and safer version of [OpenStruct](https://github.com/ruby/ostruct), allowing you to access a hash's keys via method accessors.
1334
+
1335
+ Usage example:
1336
+
1337
+ ```ruby
1338
+ default_options = { foo: :bar }
1339
+ options = Compony::MethodAccessibleHash.new(default_options)
1340
+ options[:color] = :green
1341
+ options.foo # => :bar
1342
+ options.color # => green
1343
+ ```
1344
+
1345
+ This part of Compony is also made available under the MIT license at: [https://gist.github.com/kalsan/87826048ea0ade92ab1be93c0919b405](https://gist.github.com/kalsan/87826048ea0ade92ab1be93c0919b405).
1346
+
1347
+ ### RequestContext
1348
+
1349
+ The content blocks, as well as Form's `form_fields` block all run within a `Compony::RequestContext`, which encapsulates useful methods for accessing data within a request. RequestContext is a Dslblend object and contains all the magic described in [https://github.com/kalsan/dslblend](https://github.com/kalsan/dslblend).
1350
+
1351
+ The main provider (refer to the Dslblend documentation to find out what that means) is set to the component. Additional providers are controller's helpers, the controller itself, as well as custom additional providers that can be fed to RequestContext in the initializer.
1352
+
1353
+ To instantiate a RequestContext, the following arguments must be given:
1354
+
1355
+ - The first argument must be the component instantiating the RequestContext.
1356
+ - The second argument must be the controller holding the current HTTP request.
1357
+ - Optional: any further arguments will be given to Dslblend as additional providers.
1358
+ - Optional: the keyword argument `helpers` can be given to overwrite the `helpers` context. If not given, the helpers will be extracted from the controller.
1359
+ - Optional: the keyword argument `locals` can be given a hash of local assigns to be made available within the context.
1360
+
1361
+ RequestContext further provides the following methods on its own:
1362
+
1363
+ - `controller` returns the controller.
1364
+ - `helpers` returns the helpers (either from the initializer or the controller).
1365
+ - `local_assigns` returns the locals that can be given to the RequestContext on instantiation through the `locals` keyword argument.
1366
+ - `evaluate_with_backfire` is `evaluate` with enabled backfiring.
1367
+ - `component` returns the component the RequestContext was instantiated with.
1368
+ - `request_context` returns self. This is for disambiguation purposes.
1369
+ - Any call to an unknown method will first be evaluated as a potential hit in `locals`. Only if no matching local is found, Dslblend takes over.
1370
+
1371
+ # Contributing
1372
+
1373
+ Compony is Free Software under the LGPLv3 and you are most welcome to contribute to it.
1374
+
1375
+ - If you spotted a security vulnerability, **do not open an issue** but instead use the contact form at [https://kalsan.ch/#contact](https://kalsan.ch/#contact) instead (English is just fine, even if the website is in German).
1376
+ - If you'd like to contribute feedback or discuss something, please open an issue.
1377
+ - If you have an idea that is worth implementing, please fork the repo, implement your changes in your own fork, and open a pull request.
1378
+
1379
+ # Caveats
1380
+
1381
+ - The API is not yet as consistent as I'd like it. Examples:
1382
+ - `content` replaces the content and `add_content` inserts some, but for actions the insertion is called `action`.
1383
+ - Every DSL call, in particular nested ones, should be able to insert and/or override a precise call in the parent class. Override behavior should be made consistent across the entire Compony DSL. For instance, it makes no sense that `add_content` uses an index while `action` uses `before` with a keyword.
1384
+ - Instead of `skip_...` methods, `remove_...` should be implemented. This allows yet another level of classes to re-add properties. Skipping should be kept for options given via the constructor.
1385
+ - Change resourceful hooks as follows:
1386
+ - Verb DSL hooks still take precedence over global hooks, but if given, they MUST provide a block.
1387
+ - If global hooks are present, they will be executed in every verb.
1388
+ - At this point, I haven't gotten into Turbo Streams and Turbo Frames. It would be interesting to extend Compony such it also makes writing applications using these features much easier.
1389
+ - Feasibility:
1390
+ - The feasibility framework does not yet enforce prevention, but only has effects on buttons. Actions should be structured more explicitly such that prevention becomes as tight as authorization.
1391
+ - Feasibility for links is not yet implemented.
1392
+
1393
+ # Acknowledgements
1394
+
1395
+ A big thank you to Alex and Koni who have patiently listened to my weird ideas and helped me developing them further, resulting in a few of the key concepts of Compony, such as `param_name`, or the way forms are structured.
1396
+
1397
+ Further, it should be acknowledged that Compony would not be what it is if it weren't for the awesome Gems it can rely on, for instance Rails, CanCanCan, SimpleForm, or Schemacop.