The course "Web programming languages" (based on Ruby) from MSTU. N. E. Bauman on Tehnostrim channel



    In this article we will talk about the course "Web programming languages" , which is read at the department "Computer systems and networks" (IU-6) of MSTU. N.E. Bauman. Examples are provided in Ruby, and the course itself consists of 16 video lectures, available free of charge on the Tekhnostrim channel . In Bauman, the course is read for second-year students who are already familiar with high-level programming languages, such as Pascal, C ++, or Java. The main focus is on a systematic understanding of the technologies used in web programming, and not on the depth of development of the Ruby technologies. Therefore, the course will also be useful to students who have fragmentary knowledge of web technologies in any languages.

    Content


    1. About the course "Web programming languages"

    2. Lecture Content

    3. How to create a course for the university
    4. Why Ruby?
    5. Why is Ruby not popular?
    6. Summary

    Web programming languages


    Why is the course called “Web programming languages”? The answer is very simple. As 30 years ago, when the Internet was only emerging, so now there is no possibility to use one programming language.

    • Markup languages ​​are HTML and CSS.
    • Configuration and data exchange languages ​​- JSON, XML, YAML.
    • Browser programming - Javascript (Typescript, Coffeescript ...).
    • Server programming - Ruby, PHP, Perl, Java, Javascript ...

    To understand web programming, even in a minimal amount, it is required to know 4-5 markup and programming languages ​​(although the boundaries between them are now blurred).

    Course purpose


    The main objective of the course is to build an understanding of the technologies necessary for web development, since most modern projects are somehow related to web development. The course is arranged in such a way that in a compressed form to give the listeners the basics that can be used as a framework for in-depth study.

    The students develop their specific skills independently during the training, and the degree of development depends on whether you intend to immerse yourself in web development in the future.

    Course author


    The main developer of the course is a Candidate of Technical Sciences, an associate professor at the Department of Computer Systems and Networks at MSTU. N. E. Bauman Samarev Roman Stanislavovich. A programmer with more than 20 years of experience (C ++, C, Java, Perl, PHP, Ruby, etc. for Windows, Linux, Embedded Linux, MacOS), head of software development, researcher in the field of DBMS, data processing and big data, worked in Russia, in Germany and in the USA.

    Duration and format


    The full course includes 192 academic hours: 16 lectures for 2 hours, 8 seminars for 2 hours, 48 ​​hours for 12 laboratory work. The rest of the time is allocated for self-training. Video materials include only the lecture part. Those who wish to dive deeper into the topic of the course, laboratory materials and seminars will have to learn on their own. All questions can be asked to the teacher: samarev@acm.org .

    results


    As part of the training course, we form students not only an understanding of specific web technologies implemented in the Ruby programming language, but rather a holistic perception of the problems encountered in creating web applications and everything that accompanies them, using Ruby as a very successful illustration. The Ruby language itself is a useful addition for students that can be widely used outside the course.

    Course content


    Lectures 1-2. Introduction

    • An introduction to web programming from a basic architecture perspective.
    • Minimal information about markup languages ​​and style sheets.
    • Minimal introduction to javascript.



    Perhaps, Javascript should have been allocated much more time, but since browser web programming is not the main goal of the course, and Javascript server programming technologies are not yet established, the material available is enough for an initial understanding.

    Lectures 3-5. Ruby

    The following three lectures are devoted to Ruby, since it is the technologies in this Ruby language that form the basis of the course. Lectures include:

    • Basics of Ruby.
    • The necessary information about the type structure and object model.
    • Functional style.




    Lecture 6. Principles of building web applications

    • Common Gateway Interface.


    Someone will say that this standard is not relevant, but it is the basis of all modern web programming. Therefore, any web programmer is simply obliged to know what it is, and must understand that the simplest web application is just put 'Hello World'.

    Lecture 7. Rack

    • Rack is an intermediate layer for most Ruby web frameworks.
    • Sinatra is a common framework for creating simple applications.
    • An example of creating an application.


    Lecture 8. Introduction to Rails

    • Key aspects of Rails applications.


    Ruby on Rails is the same framework that made Ruby famous and almost became its synonym. This is one example of a deeply crafted Model-View-Controller framework that served as a prototype for creating many other web frameworks, including Grails and Django. Note that the concept of Rails: generate as much code as possible using automatic generators and write less with your hands.

    Lecture 9. Asynchronous interaction

    Most modern web applications use the asynchronous method, that is, requests to the server are left in the background for the user. Answers are processed somewhere in the depth of the browser. What you need to know?

    • Exchange formats are XML and JSON.
    • Run an asynchronous request from Javascript.
    • The concept of unobtrusive Javascript applied to Rails.


    Lecture 10. Testing

    Any modern programs should be covered by automatic tests. Ruby involves the use of unit tests. And, of course, Rails assumes that any action should be covered by tests. The lecture includes the following topics:

    • Testing various aspects of web applications.
    • Introduction to domain languages ​​(since RSpec and Cucumber are the very examples of “humanity” in tests: a testing program should be understandable not only for a programmer who is “sharpened” under the language used, but also for a normal person). Note that the approach used in both RSpec and Cucumber is now widely replicated in test tools for many other programming languages.
    • Tools like SikuliX and Selenium, which can be used to test programs with a graphical interface and browsers, respectively.


    Lecture 11. XML Technologies

    • Query languages ​​such as Xpath, Xquery.
    • XSL and XSLT.


    It would seem, what does all this have to do with web programming? But XML is at the core of web technology. The fact that now we do not use XML as an exchange format does not guarantee at all that in 5 years we will not begin to do it again. There is still no unified approach to data verification in JSON format. And in the case of XML, the markup scheme is laid down by the language itself.

    The query language Xpath is, in fact, a universal language for trip queries, which can be used to search for any elements of tree data structures, which also includes JSON.

    XSLT transformations are also another way to transform XML documents, the knowledge of which will allow students not to reinvent bicycles in the future when they encounter ETL.

    Lecture 12. ORM (Object-Relational Mapping)

    Virtually any modern web programming framework provides any means for object-relational mapping. Students need to understand:

    • why such a mechanism is needed;
    • what are its limitations;
    • how to use it in practice.

    In this case, everything is considered in the context of Ruby on Rails.


    Lecture 13. Sessions, security and everything connected with it.

    • The state storage method based on cookies.
    • Typical authentication methods.
    • An example of adding authorization in Rails.
    • Security issues of web applications per se.


    Lecture 14. Services

    • Historical aspects.
    • Specific recommendations for the development and deployment of their own services for the Web.


    Lecture 15. CMS (Content Management Systems)
    In web programming, it is important not only to be able to write an application, but also to understand whether you need to write it. This lecture is a demonstration of the main types of already created web applications that can be customized to the requirements of a specific customer and, if necessary, modified.

    • Emphasis on Ruby tools.
    • The most common CMS written in PHP.


    Lecture 16. Placing Ruby Web Applications on the Internet

    The general ideology of web services is considered. The origins of this architecture with the interchangeable XML format and its further modification in the Web API with JSON and REST or GraphQL are explained.

    • Web servers.
    • Virtualization methods.
    • Ways of placing an application on the Internet.


    How to create a course for the university


    It is difficult to create training courses on topics related to programming, where technologies change every 5-10 years. When creating a course for a university, it is necessary to balance between the development of practical skills in specific programming languages ​​and the presentation of the theoretical foundations necessary for understanding technologies as such. And besides, the difference between university education and training courses lies in the systematic presentation of material, which also imposes restrictions on when and in what volume certain material can be submitted.

    In recent years, there has been a tendency to record university lectures on video and create video courses. Course "Web programming languages"is the first such official attempt by our university. And based on the feedback, we will decide how and in what format to make new entries.

    10 years ago it was necessary to radically update the curriculum, introducing, including, web programming. At the department "Computer systems and networks" for courses related to electronics and computer design, traditionally allocate about the same training hours as in programming. Moreover, programming courses include algorithmic training in high-level languages ​​Pascal, C, C ++ / Qt, training in various assemblers, as well as theory of programming languages ​​and compilers. And even languages ​​for programming FPGA and specific hardware. That is, the department prepares universal specialists, who in the future themselves choose specialization.

    We needed to identify promising web technologies that can be mastered in a semester, and it is desirable that these technologies can be projected into other programming languages.

    Why Ruby?


    Why is Ruby chosen? The choice of languages ​​for web programming is quite rich. In addition to Ruby, this includes PHP, Perl, Javascript, Java, Go, and others. If we approach from the point of view of high-load web applications, then sending doubters to the Web Framework Benchmarks , we see C ++, Java, Rust, Ur, Go, etc. in the front row. Ruby is neither the most popular for web development nor the fastest for high load solutions. However, Ruby has a lot of other advantages that make it a programming language that any educated programmer should have an idea about.

    Recently, Ruby celebrated its 25th anniversary, that is, it is a fairly mature language. Despite the fact that most of the mentioned languages ​​have also stepped over or are close to this age (Rust, Dart, Go is still "green" in comparison with it), Ruby is one of the few languages ​​that maintains backward compatibility throughout these years.

    In the world of Ruby, one might say, there were no revolutions and some radical changes. It belongs to the initially well-designed languages, the basic concepts of which have reached this day without changes. Performance claims related to older versions prior to 1.8.7, which were discontinued 10 years ago. Modern versions each year demonstrate a multiple increase in productivity. Claims that this language is not very popular are valid only for our country. Unfortunately, we have large companies really undeservedly bypass it.

    Why is Ruby good for university education? This is a pure object language. And since it is dynamic, almost everything can be redefined. There are no simple types in his model (we will not think here about system implementation, we are only talking about the model). Any data is an object. Code is an object. That is, Ruby makes it easy to learn the principles of object-oriented programming. In addition, the language syntax is quite simple and has almost no exceptions. Any code written in the program must be executed once, and no matter where this code is written - inside the class declaration or outside. Whatever is written, it will be executed. Ruby's syntax is very flexible, which makes it very convenient for writing domain-oriented languages ​​(DSL / DSEL). In addition, the basic concept of Ruby - block - is an anonymous function.

    And, rather, the decorative advantage of Ruby is that you don’t have to waste time explaining the mandatory formatting of the code indented. The program is clearly labeled in any case. Formatting will automatically provide rubocop, and students will learn to write correctly over time.

    Why is Ruby not popular?


    Why is it that Ruby, having such advantages, is still not popular and refers to languages ​​with a high threshold of entry?

    The first thing to be understood: Ruby is not just another imperative programming language in which you can start programming in the evening, but in a week to comprehend completely. This is a different language with a different philosophy.

    The first principle of Ruby: program text should be perceived as natural language text. That is, Ruby is a language for a programmer who is a human being and not a language for which a suitable programmer must be selected. Unfortunately, most modern programming languages ​​follow the principle “the programmer can endure everything,” and the retreat is already perceived with difficulty.

    Ruby is often criticized for doing the same thing in a dozen ways. But in natural language we have a huge number of synonyms, and it is the choice of the right synonym that makes our speech rich. So it’s in Ruby. In addition to the fact that the same actions can be performed in different ways, there are many synonyms associated with the special methods alias and on the same methods alias_method.

    A simple example of the limitations of most other programming languages. Suppose there is an array of products, and you want to determine that it is not empty. In most languages ​​we will write something likeif (products.size() > 0) ... But, having come to the store, we do not ask the seller: “If you have more than zero of such a product?”. We ask a simple question: “Do you have such a product?”. In Ruby, you must use methods that express the meaning of the action. Yes, we can use a “more zero” check, but the natural way is to ask if products.any? That is literally: are there any products? Note that Ruby works well with Unicode, so if necessary, based on this language, you can create specialized languages ​​with regional adaptation. For example, if you want to override in Russian all the names of classes and methods.  

    An interesting, though not entirely direct example: Bato: A Ruby port for Filipinos .

    On the subject of language objectivity: in Ruby, variables / constants and objects are clearly separated. Due to the dynamic nature of a language, data “lives” its life as objects. Any identifier is a constant or variable that merely refers to an object. Failure to understand this principle leads to surprises:

    str1 = "Test"
    str2 = str1
    str1.sub! "Te", "La"
    puts str2 # => "Last" ???? Мы же меняли str1, что случилось?..

    Here we just used the modifying method of the object, references to which were stored by two variables. Note that this is not a Ruby change method. Typically, objects remain unchanged, and changes generate new objects. In addition, the method used here sub!has a suffix — an exclamation mark — that is a Ruby naming scheme for methods that modify the object itself. Without this symbol, the method will simply generate a new object.

    Another feature of Ruby that very often baffles developers coming from other programming languages: the concept of "block". Syntactically, the block looks the same as in other programming languages, and in two versions at once: {…}anddo..end(do not forget that Ruby is created for a person, so we choose for better readability of the bracket, if the expression is single-line, and words, if there are many lines). The essence of a block in Ruby is code that is stored as an object and can be activated by a call yield. Direct analog in C and C ++ are callback functions. In Javascript - anonymous type function some_func('on_element_click', function(event) {…}).

    Thanks to this concept, Ruby is one of the most concise and expressive programming languages. For example, the conversion of array elements in accordance with the squaring function will look like this:

    (1..5).map { |x| x * x } # => 1, 4, 9, 16, 25,

    where { |x| x * x }is a block with a declared local variable x, that is, a function that converts the elements of an array. And the method to which it is passed is simply called map (that is, “display”). And you don’t have to write a word return, although this is possible, because everything is clear (in Ruby, the result of the last operation is always the return value). Moreover, the block code is a code called autonomously for each element of the array. That is why it is pointless to try to create variables inside the block and hope that their value will remain when processing the next element. A block is a saved processing function, and no more.

    If we want to parse the string with the numbers entered from the keyboard, it suffices to write:

    gets.chomp.split.map(&:to_i)

    That is, read the line (gets), discard any garbage like newline characters ( chomp), break into words ( split), call the conversion with the function to_i(strictly speaking, the method of objects of the type "string"). And nothing more. Split knows that in a normal human language, “breaking a string” means dividing it into words, where delimiters are spaces and punctuation. Map can be used in such a short form with the name of the method to be taken from the object. Although one could write a complete form map { |x| x.to_i }, or even { |x| return x.to_i }. But this does not improve readability, so you can leave it simple map(&:to_i).

    Note that the concept of the block frankly permeates Ruby. Even the view code

    classHelloWorld
      (1..3).each { puts 'Hi from class declaration!' }
      defhi
        puts 'Hello World!'
      endend
    HelloWorld.new.hi

    displays: What may seem unexpected here? The loop inside the class declaration has output messages. Then we received a message from the instance method of this class. And the secret is very simple. Ruby is a language with a regular programming model. Typical way to call any method with a block:

    Hi from class declaration!
    Hi from class declaration!
    Hi from class declaration!
    Hello World!




    method_with_block(args) do
    ...
    end

    Words class , and def in the example, in fact, are the names of the methods that are passed arguments HelloWorld, hi. The argument HelloWorld will become for us the constant-name of the class, and the hi name of the method. The rest of the word end is a block. And the block code is activated by calling yield, after which everything is executed sequentially. That is, even here there is practically no difference between calling the usual method and declaring methods, classes, modules.

    Also pay attention to the activating design HelloWorld.new.hi. HelloWorld- constant - indicates an object of type Class. This object has a method new. The result of the call newis a created object of the type HelloWorldfrom which we call the methodhi. And even here the regularity of Ruby appears. We do not write something = new HelloWorld, but simply call the method of a specific object ( Classreferenced HelloWorld), which generates an object of type HelloWorld.

    Long call chains also contribute to misunderstanding of the language:



    If you know JavaScript or jQuery, then you see nothing particularly scary here. Those who come from C and C ++ may be puzzled about the number of points. Ruby uses a functional object transformation. That is, this whole chain is the process of converting a string, consisting in selecting words, converting them into numbers, selecting only even ones, squaring and adding the result.

    Any method in Ruby spawns a value object. There are no exceptions. Even nil is an object. Since Ruby is a dynamic language with an automatic garbage collector, there is no need to create new variables. Intermediate objects will be deleted. That is, a long expression can be easily disassembled into a sequence of assigning values ​​to local variables, which the corresponding methods sequentially call. But why, if everything is clear?

    In a Ruby program is extremely rare to see the type of cycles for, while, loop. They are provided in the syntax, but almost not used. Why? Yes, because they do not carry semantic load.

    Example: in the array of goods it is necessary to find a “bun with poppy seeds”. For traditional programming languages, we can use approximately the following Ruby code:

    products…# какой-то массив с объектами — товарами.
    found_product = nilfor i in0...products.size do
      if products[i].name == 'булочка с маком'
        found_product = products[i]
        break
      endendif  found_product != nil
      # Булочки нашли, делаем что-то полезное.end

    At the same time, normal Ruby code looks like:

    products… # какой-то массив с объектами-товарами
    found_product = products.find { |product| product.name.eql? 'булочка с маком' }
    unless found_product.nil?
    # Булочки нашли, делаем что-то полезное.end

    That is, we write literally in one line: find a product by name. And that's all. Because we are really only interested in the selection of goods, and not at all the indices of goods and not their quantity.

    Life example: you came to the store and asked the unfortunate seller in two ways: first - “ For all products from zero to 15143, if the name of the product is equal to a bun with poppy seeds, then give it to me ”; the second is “ Give me a poppy seed bun .” It seems that both options are syntactically correct, but the second is natural. Most programmers for some reason consider the first option to be normal. And Ruby programmers are second. And the method find here is simply as one of the substitutes for the cycle. I draw attention to this by anticipating remarks that in other languages ​​there is also a search for an array with a selection function.

    So, although Ruby has a syntactic structure for, whileand looptheir almost nobody uses, because there are specific methods: each, each_index, each_with_index, select, map, reduce, find, detectand many others that express a specific meaning - for each index for each item and its index, select, convert, collapse, find, etc. And if we need to get the indexes, we will use array.each_index. And if you need to select elements, use select. Focus on naturalness. We ask only what you really need to do. No index is needed - there’s no need to ask for it. For more information, see the documentation for the Enumerable module .

    Summary


    Ruby is a syntactically simple but flexible language with a developed object model, the main accent of which is a concise, but well-perceived code oriented towards a living person. Ruby is present by default in the bundle of any modern operating system (or may be installed in Windows). There are a huge number of programs written in this language, there are stable communities ready to help with advice or action. Ruby programs are basic administration scripts for Linux and MacOS (OpenSuSE / SuSE and brew.io respectively), this is math and machine learning , these are tests (Rspec, Cucumber, Capybara ...), this is application deployment (Puppet, Chef) and much more.

    If students know Ruby, this will significantly broaden their horizons, allowing them to take a completely different look at familiar things. In addition, after Ruby it is very easy to learn other scripting programming languages, but the question is: do you want to use them?

    Also popular now: