📜 ⬆️ ⬇️

Chat on rails

Today we will create an application on Ruby on Rails, aka Rails, aka RoP. ( Ruby on Rails, RoR, Rails ). For the sake of brevity, I will use the expressions “rails,” “rails,” or “rohr.”

The application will be slightly different from most examples for dummies, and will focus on the demonstration of Ajax libraries intergrated into the rails for dynamic page refresh and special effects. What could be more visible for this than chat? Is that stock quotes. But we still do chat

Although this is not a tutorial, but a demonstration of possibilities, you can easily repeat all this on your system. All you need is a mysql server, and at least version 2.0 rails. The only difference from the earlier ones, in the framework of this example, is the pattern suffixes (.rhtml in the first, .html.erb in the second).
')
I did this on Ubuntu Hardy 8.04, but this should work on any platform, in the case of windows, with obvious differences in the form of a separator in the paths.

I regret to say that Habr administrators have not bothered to ensure the normal input of unshielded CTML and SGML code (and screened too: try to enter “less” -! DOCTYPE ...), therefore all the code that needs to be entered into the project files , I bring in the form of pictures, so you have to interrupt the code manually, if you want to repeat it. On the other hand, I promise that no file goes beyond the standard 80x25 terminal, so there is not much work to do. Again, re-use is useful for mastering.

Before you begin, I strongly recommend that you make sure that your mysql server creates databases in the default utf-8 encoding, and it also uses it when connecting from clients. If not, you'll have to add the key to the mysqladmin command below. Also, I don’t like to write “-u root” with every mysql call, so in the [client] section of the my.cnf file, I have user=root .

Let's start:
rails chat; cd chat


Now the base:
mysqladmin create chat_development


In this mega-project, we will have a whole one table about two columns: a nickname, and a message. You can create it with your hands, but we don’t love it with our hands, so we’ll do it properly, through the migration of rails. This will help us in the future.
script / generate migration create_conversation

In db / migrate / 001_create_conversation.rb after def self_up add:



Rails will add us the columns “id”, “created_at” and “updated_at”, and will automatically take care of their content. We start the migration, and the table will be created:
rake db: migrate


For decency, you sometimes need to display something to the user in a browser. Create a common app / views / layouts / chat.html.erb template like this:



The most interesting place is the sentence <%= yield -%> , which actually displays the contents of a particular template. We describe them later.

Now the controller. Like the entire application, it is extremely primitive. Let's create
app / controllers / chat_controller.rb with this content:


Message.find displays the last 30 messages (Select From), focusing on the "id". For good it would be necessary for “created_at”, but it was too painful to write laziness.

Message.create message adds (Insert Into) as easy to understand.

As part of this entertainment, we cannot afford the user management system, so we simply assign a digital nickname to visitors. If he bothers them, they shake "New nickname", and we give them another.

We need templates. A template is a file that is named by default in the same way as a controller share. In other words, after working out def say by default (and we like the defaults), the template say.html.erb will be called (in the old script - say.rhtml ). Create a template directory for our only chat controller.
mkdir app / views / chat


The center of this project is the output template app / views / chat / index.html.erb :



That is written by everyone! Let's sort it in pieces.

The fact that :partial is simply inserting a code fragment from another file, see below.

form_remote_tag will create for us the usual CTML form, but with attachments in the form of Ajax calls from the prototype and script.aculo.us libraries, due to which we can not issue normal POST and not redraw the screen. The main parameter of the call is :update , which tells us which element with which id in our page will receive the result of the action specified in :action . The default controller is the same “chat”.

link_to_remote works much the same way, we use it to replace the nickname.

periodically_call_remote is our shame. Never do chats like this. And do them with the help of a plug-in for mongrel (or another web server), which can provide server-push in case of new messages. But since everything is very primitive, we simply reboot the div with the chat body. Every 10 seconds (default, yes).

A fragment (partial) is a piece of a template that can be used repeatedly, like a function call. We will need to redraw the main window with the contents of the chat in different places, so create a fragment app / views / chat / _conversation.html.erb :



UPD: at the request of local hackers, we literally added a couple of characters to this fragment, so that the malware would not insert the code into its replicas.

In the index template, we have already seen his call. It is also called in the say template. Create app / views / chat / say.html.erb :



When you press enter after filling out the form, the action say called. Find in the controller code def say .

And the last. The latest versions of ro ​​have implemented ways to protect against substituting the contents of forms within a session. By default, they are included, but they will interfere with us, since we can throw out the session, and then submit the same form, using the Ajax. Therefore, you need to fix app / controllers / application.rb . Find there the line starting at protect_from_forgery and comment out. Oktotorpom in the first position.

The project is ready. We start the server:
script / server


See what happened: localhost:3000/chat localhost:3000/chat .

What did we do? The code is, as usual in such cases, a bloody mess of a scripting language, ERB, HTML, CSS, esquel, and javascript. But thanks to the efforts of the developers, Rohr, according to the general opinion (with whom I fully agree), the architecture and tools of the rails enable us to make this mess still less bloody than usual, and write as much code as possible in the most aesthetically preferable language, on ruby. SQL has come down to the “id DESC” stub, and javascript to the prototype $ ('sentence') call so that we always return the focus to the input box. The prototype (and the rail wrapper around it) allowed us to update the page fragments in the background, and the scriptkulos lights the input field with hellish yellow fire after sending a replica, and also creates the effect of a new nickname arriving.

It would be very instructive to look at the page code. You will see how much of the faddish code on js we were saved by the rails. Try it yourself. You should have something similar to what I got: chat.gde.to/chat . Successes you on rails.

Disclaimer: This is not a translation or adaptation. All text is original, all code was created specifically for this article.

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


All Articles