📜 ⬆️ ⬇️

Ruby on Rails agreement. Part 3



No paradigm


There is an emotional attachment when choosing a certain central idea as the foundation of your architecture and following it to its logical conclusion when developing an application. There is purity in the discipline, so it is clear why so many programmers are attracted to this approach.

In Rails, it is not. This is not one perfect cut fabric. This is a blanket. The collection of many different ideas and even paradigms. Many of them, as a rule, contradict each other, if they are compared with each other and one by one. But this is not what we are trying to do. This is not one big competition in which one winner should be announced.
')
Take the templates with which we create a view in our Rails-MVC pie. By default, all the helpers that allow us to extract code from these templates are simply a large set of functions! This is a single namespace. Oh, shock and horror, it's like a PHP soup!

But I argue that the creators of PHP were right in choosing this solution when it comes to presenting individual functions that rarely need to interact, as is the case with abstraction in presentation templates. And for this purpose, a single namespace, a large set of methods, is a reasonable choice.

This does not mean that we sometimes do not want to achieve something more object-oriented when building views. The concept of Presenters, in which we conclude a multitude of methods that are interdependent with each other and the underlying data, can sometimes be the ideal antidote to soup methods attached to dependencies. But, as a rule, it turns out to be a rare case, and not common.

For comparison, we usually see the model in MVC as the main bastion of the object-oriented approach. Finding only the correct names for objects, increasing consistency and reducing connectivity is the pleasure of modeling the subject area. This is a very different layer from the presentation, so we use a different approach.

But even here we do not approach one paradigmatic dogma. Problems with Rails, a specialty of Ruby are mixins, which are often used to give individual models a very wide surface area. This fits well with the Active Record template, providing the associated methods with direct access to the data and the repository with which they interact.

Even the very core of the Active Record system offends some purists. We mix the logic necessary to interact with the database directly with the business area and logic. Such a combination of boundaries! Yes, because it turned out to be a practical way to wrap a web application, which almost always has a connection to the database in order to maintain the state of the domain model.

Being so ideologically flexible is what allows Rails to solve such a wide range of problems. Most of the individual paradigms work very well in a certain fragment of the subject area, but they become problematic when used outside their sphere and comfort zone. Applying a multitude of intersecting paradigms, we cover the flanks and guard the rear. The final structure is much stronger and more capable than any individual paradigm would allow it to be.

Now the cost of these polyamorous relationships with many programming paradigms is conceptually overhead. It is not enough just to know object-oriented programming to have a good time in working with Rails. It is also desirable to be able to work well with a procedural and functional approach.

This also applies to many sub-languages, as well as Rails. We are not trying to protect you so much so that you learn, say, JavaScript for presentation or SQL for complex queries. At least not to reach the peak of opportunities.

The way to alleviate some of these learning problems is to simply simplify getting started, do something really valuable, before you understand every single aspect of the structure. For this reason, we rush to Hello World. Your table is already cooked and snacks are served.

The idea is that by giving something really valuable at an early stage, we encourage Rails practitioners to quickly increase their level. Take the journey of learning as joy, not an obstacle.

Beauty cult code


We write code not only to be understood by the computer and other programmers, but also to enjoy its brevity and beauty. Aesthetically pleasing code is a value for itself and should be sought for. This does not mean that beautiful code solves other problems, but it should be one of your priorities.

So what is a beautiful code? In Ruby, this is often the intersection of native Ruby methods and the full power of DSL. This is an inconspicuous edge, but still worth trying to find a middle ground.

Here is a simple example from Active Record:

class Project < ApplicationRecord belongs_to :account has_many :participants, class_name: 'Person' validates_presence_of :name end 

This is similar to DSL, but in reality it’s just a class definition with three class method calls that take characters and parameters. This is nothing ordinary. It is readable. It's simple. This gives a large amount of flexibility from several definitions.

Part of the beauty of this example is that it is in line with previous principles, such as the Convention on configuration. When we call belongs_to: account, we assume that the foreign key is called account_id and that it is in the projects table. When we need to define the class_name Person for the participants association, we only need to determine the class name. From this we will again obtain foreign keys and other configuration points.

Here is another example of database migration:

 class CreateAccounts < ActiveRecord::Migration def change create_table :accounts do |t| t.integer :queenbee_id t.timestamps end end end 

This is the strength of the framework. The programmer declares a class in accordance with a specific agreement, for example, a subclass of ActiveRecord :: Migration, which implements the #change method and the framework performs all the related operations and knows that this is a calling method.

This makes it possible to write less code. In the case of migrations, this not only calls rails db: migrate to update the state of the database to add a new table, but also allows you to delete it if necessary. This is very different from how a programmer does all this and combines libraries that invoke themselves.

Sometimes a beautiful code has a shorter record. It’s not about doing something as short or as powerful as possible, but about following the concept of an agreement.

These two conditions do the same thing:

 if people.include? person … if person.in? people 

The concept and focus are somewhat different. The first condition focuses on the collection. This is our subject. In the second condition, the subject is clearly a person. There are not so many differences between these two conditions, but I argue that the second is more beautiful and will make me smile when used in a place where this condition applies to a person.

Sharp blades


There are many sharp blades in Ruby. Not by chance, but intentionally. The most famous is monkey-patching: a mechanism for modifying existing methods and classes.

This unlimited power can really lead inexperienced programmers to a crooked path. People who come from a more severely constrained programming environment imagine all sorts of problems associated with this, which will ruin Ruby for the reason that it provides great confidence in programmers by allowing them to use this function.

If you can change anything, stop you from rewriting the String # capitalize function and the 'something bold'. Capitalization returning 'Something Bold' instead of 'Something bold'? This will work in your local application, but will break all the logic that depends on the original implementation.

Nothing, this is the answer. There is nothing in Ruby to stop you from using sharp blades. We seek agreement following kicks and education. Do not forbid sharp blades in the kitchen and insist that everyone use spoons for slicing tomatoes.

Because the reverse side of monkey patching is the ability to do things like 2.days.ago (returns a date two days ago from the current one). You might think this is a bad deal. The fact that you better refuse to use 2.days.ago, if it means that programmers do not overwrite String # capitalize. If this is your position, then Ruby is probably not for you.

Nevertheless, it would be difficult - even for people who give up such freedom for any kind of security - to assert that the ability to change the main classes and methods dooms Ruby as a language. On the contrary, the language flourished precisely because he proposed another radical point of view for the role of the programmer: to entrust them to use sharp blades.

And not only trusted, but also taught how to use such powerful tools. So that we can raise the level of the professional field, assuming that most programmers would like to become better programmers who can master sharp blades without injuring their fingers. This is an incredibly inspirational idea and it contradicts the programmer's intuition about other programmers.

Because it is always about other programmers when the value of sharp blades is disputed. I have not yet heard how one programmer extended his hand and said: “I cannot trust myself with this power, please remove it from me!”. It is always "I think that other programmers would abuse it." This line of paternalism never touched me.

This brings us to Rails. The blades provided by the framework are not as sharp as those provided by the tongue, but some of them are still very interesting in section. We do not apologize for providing tools such as parts of the starter kit. In fact, we should note that we sufficiently believe in the aspirations of our fellow programmers and boldly trust them.

Over time, many Rails functions begin to challenge “too much freedom.” But one example, which is currently the most popular, is the apogee. This is a thin layer of syntactic sugar around Ruby’s built-in function of modules and is designed so that one class can encapsulate several related classes, but separate concerns (hence the name).

The charge is that with the help of concerns, programmers can break their objects into separate sets and turn an obvious structure into a mess. And it is true. Concerns really can be used that way.

But the biggest mistake is not to provide such functionality as concerns, which, when used with even weakly skilled hands, allow to eloquently divide concepts, we would put programmers on the path of architectural bliss. If you cannot be trusted with cleaning the kitchen sink from an oversupply of concerns, you probably won't become, otherwise, a professional in your field.

Programmers who have not yet learned how to handle sharp blades are not yet going to make meringues. The important word here is: More. I believe that every programmer has a way, if not the right, to become a fully-fledged representative of the Ruby on Rails community. And speaking full rights, I mean knowledgeable, aware of when and in what context sharp blades from a set of tools should be used.

This does not negate the responsibility for helping them in this direction. The language and framework must be patient teachers, willing to help and guide newcomers. We have to admit that the only reliable way of learning passes through the country of mistakes: the tools are used incorrectly, some blood, sweat, and perhaps even some tears. There is simply no other way.

Ruby on Rails is an environment for chefs and those who want to become chefs. You can start with the dishes, but you can work on the kitchen. Do not let anyone tell you that you cannot trust the best tool in this way.

Source: https://habr.com/ru/post/329844/


All Articles