How I learned Ruby on Rails in three nights. And I never learned

How I learned Ruby on Rails in three nights. And I never learned

17.11.2023

I've been wanting to learn Ruby on Rails at some basic level for a long time. Without a specific goal. Rather, just for yourself, to better understand what is so special about it (unlike 100,500 other technologies and frameworks), which allows you to quickly create and scale fairly loaded Internet projects. A secondary reason was the desire to try new approaches to learning. When I was studying to become a programmer, we only had books and forums where you could ask for advice. Now there are interactive textbooks and online programming schools, a huge number of screencasts (almost a dream: watching gurus program), knowledge bases like stackoverflow.com and tons of source code on GitHub, where you can spend hours studying the source code of real pros. I decided to set aside the next few nights (and there was simply no time during the day) to try new ways of learning in action.

Night one

Starting to learn Ruby on Rails without at least minimal knowledge of Ruby itself would be strange. I already took on the interactive guide ruby-lang.org. But as soon as I passed it, I immediately forgot everything. Its creators promise that it will take fifteen minutes to complete and master the syntax of Ruby. It took me thirty. True, with constant distraction on Twitter. The process looks something like this. They tell you: “Arrays in Ruby are declared like this, and data is retrieved from arrays like this. Now let's try to make an array and extract N elements from it. We'll check." You read how everything works and try it right away. Of course, you won’t learn Ruby this way. It’s better to think of it as a super-express course that works.

And yet Ruby itself is very far from the Ruby on Rails framework. I wanted to master the rails. From our article about online education, I definitely remembered the sensational Zombie for Rails course railsforzombies.org. It's the same as Try Ruby, an interactive tutorial that teaches you how to build rail applications right off the bat. First, they give you a mini-lecture (in English, but everything is very clear - turn on subtitles) about the file structure of a rail application, the CRUD approach to working with data, they explain how the MVC model is implemented in rails, and so on. After each video, you are asked to complete tasks to consolidate the material. Everything seems simple and clear, the course flies by unnoticed in an hour or two (it is short). But! After the course, did I feel like I could write a rail application? Unfortunately no!

Night two

One of the reasons why after Rails for Zombies you have some basic knowledge, but no confidence, is the virtual environment in which the training takes place. On the one hand, it reduces the entry threshold to the limit: you don’t have to worry about your surroundings. On the other hand, you don’t create anything real along the way - no “Hello World” for you at the exit. And most importantly, from which side to approach its creation is unclear. From that moment on, I wanted to try Ruby on Rails in action, actually installing it on the system (before that I didn’t even have to try), and create a simple application from scratch.

I don’t remember how, but quite by accident I came across a very successful screencast course in Russian rails.hasbrains.org. Thanks to the author for his competent presentation: he methodically explains the principles of operation of the rail application in detail, immersing you in all the necessary subtleties along the way. Long story short, I spent the entire second night of the experiment watching the first half of over thirty episodes of these screencasts.

The picture of how an application is generated, how to work with the rail console, how to create models and migrations, how to update models and how to validate data in them, RESTful controllers, and so on has finally been fixed in my head. Watching each of the episodes, I immediately tried everything in action, building a fully working rail application. It became clear how the rails are designed in principle.

Night three

On the third night, the last episodes of the screencasts remained, which I managed to watch in one sitting: working with rails no longer seemed so wild. At that moment, someone told me that the Rails for Zombies course had a sensible and much deeper continuation. True, the course is already paid and is hosted within the Code School programming school www.codeschool.com. It wasn't a shame to pay 25 bucks to get access to all the school's courses. This is a monthly price, so if you don't like it, don't forget to cancel your subscription.

The Rails for Zombies 2 course turned out to be very successful indeed. True, a lot of it was a repetition of what I saw in the screencasts, but it was even partly pleasant. Five levels and five blocks of exercises that you do directly in the interactive console. By this point, the rails already seemed logical, understandable and usable.

In Code School you can program directly in the browser while completing course assignments

What's next?

Have I learned how to do complex projects? No. But I definitely realized the approaches used in the rails and understood their convenience. I learned how to quickly create simple applications and increase its functionality in a super short time using gems written by the community. I caught the courage and continue to enjoy learning the best practices using Code School programs (I’m currently taking a course on unit tests). And it makes me damn happy that learning technology has become so easy.

Guys, the course is fire, everything is fire!!! Starting from the very basics and moving on to more complex things, the course provides both a theoretical basis and a lot of practice. The course is aimed at ensuring that the student builds the right thinking in his head from the point of view of a programmer. I really liked this course, I recommend it to everyone, both beginners and those who are already familiar with the basics of programming. Thanks to the guys for their valuable work and experience!

Very good course - well done guys. Gradually, the brain is filled with all the minimum necessary for the life of a programmer and then added with more advanced goodies.

The presentation of the material is just fire, it was so interesting to watch all the videos and then go through homework, just one thing confession of a Php student what is it worth and everything is there.

An individual approach when accepting homework (not on a formal basis) - depending on your performance, teachers may complicate the task for you or ask you to do it using more advanced technologies.

What’s very cool is 24/7 support in Slack!

Awesome webinars that include debriefings and more - I watched some of them several times because the material is very important and very well explained.

But the most significant thing for me was that the courses immerse me in a completely different state - a state of constant comprehension of something new, the pursuit of knowledge - and this is most important - it’s like a motor that was started in me and now I move thanks to it. Thank you very much to the teachers for giving me a new life, filled with the desire for knowledge, grief from what doesn’t work, and joy from what I fixed.

The course is simply wonderful! A clear explanation of the material, regardless of its complexity. Many thanks to the teachers! They quickly answer questions and give reasonable and specific feedback on the tasks being performed. The result speaks for itself: 5 months, and I successfully passed the interview. Great course! It's worth going through!

Ruby on Rails developer, Taganrog, github

Awesome course. Rich, not boring, to the point. Great teachers. I didn't find any cons at all. Treated like a human being. I came as a complete newbie. Now I'm a super newbie! I wrote a program in ruby ​​(more than one), wrote an application in rails (more than one), configured a server, deployed the application, attached various functionality to the application, figured out domains, ssl certificates, dns, authorizations and much more. I'm eager to fight, taking on an independent project. In general, thank you very much, Good Programmers!

Ruby on Rails developer, Moscow, github

In principle, I had no intention of taking the course, but the way these guys present the material makes me want to work with them, learn, and just communicate with them.

The key advantage of the course is the fact that the guys really love and want to teach people. The course is NOT in the “Well, we gave you the material there, and then figure it out on your own” format, people put their soul into it and worry about how you perceived the material. After completing this course, you can safely go to work as a Rails developer.

Ruby on Rails developer, Krasnodar, github

The main points used in developing a web application are clearly explained. The most popular gems in rails are also discussed.

They check their homework well and give detailed comments. I appreciate the fact that the guys don’t give up on you after finishing the course and keep in touch, helping in word and deed)) The site is not very convenient in terms of finding information, especially when you finish all 71 lessons, but I think the guys will work on it, otherwise there’s nothing to complain about.

Team lead at AirBnB, San Francisco

I have significant experience in online learning - this is the best online course I have ever encountered. Everything has been worked out - high-quality material, excellent presentation. And most importantly, after the course you can really become a programmer!

I live in Silicon Valley, go to various meetups and workshops, meet graduates of vaunted local bootcamps (whose cost, by the way, starts from 12 thousand dollars for 4 months) and I understand that my knowledge after the course is many times greater than many graduates of these famous Silicon bootcamps valley, despite the fact that I started from scratch and had never opened a terminal before “Good Programmer”))

I will wait for a work permit and will definitely get a job. After the course I feel the strength to do this, I know that it is possible! Thank you guys!

In my opinion, the guys have created an excellent course that is suitable for both completely new programmers and those who already have experience working with other languages ​​and libraries.

Excellent material and presentation, overall attitude, and atmosphere during the webinars. The guys work hard to help each student, if necessary, they will chew to the smallest detail. After the courses, you feel confident in your abilities, you understand that getting a job in the IT field is quite possible, if you have the desire.

The foundations for a basic understanding of programming are well provided. Interesting and real problems are given, the solution of which will help and be useful in the future.

Let me summarize. I consider this course to be one of the best, and I definitely recommend it to anyone who has decided to devote their life to the field of programming. At the moment, in an active search for work, the demand is quite high, therefore, everything is in your hands! I express my deep gratitude to the guys and wish them success in the future!

Ruby on Rails developer

The course helped, I learned how to program in Ruby and on rails, I’m not a super-cool programmer, but I know that I can write anything, I may need to do some additional reading.

The goal was “learn to program and find a job.” The task was completed 100%, I learned how to program, and they hired me.

"Hello! What are you doing?" - “Yes, I’ll program one thing in Ruby.” - "Is it contagious:-)"
This is the dialogue I had today with a friend. Why ruby?

Why learn Ruby

This question concerns those who have been programming in PHP for a long time and successfully. You've mastered one language, that's great, but don't stop there. Many may argue that they know the language, are familiar with it and have already learned all the tricks with it. I'll give you a few reasons to learn Ruby.

  1. Curiosity. For example, I was very interested in working with open classes. Just like that, taking and injecting your method into a system class is great, in my opinion. Won't there be confusion? And how to do it? In general, everything new is interesting.
  2. . Because I’ve been programming in PHP for a long time, I’m wondering what Ruby can boast of over PHP/
  3. Ruby speed. Twitter was made in Ruby (although it has recently been abandoned). I would like to test its performance in reality.
  4. Class of problems to be solved. Ruby is good for web applications. Is this so?
  5. Metaprogramming. Perhaps the most important reason.

How to learn Ruby. Syllabus.

This is where my first mistake was that I started learning the framework without knowing the language. Now I realized that there is no need to do this. Forgetting for a while about Ruby on Rails, I began to study Ruby itself, fortunately, there was a system problem hanging in the ticket system for a long time, which was difficult to solve in PHP. I really didn’t want to give him root rights So this is the plan.

  1. Functions, classes, public classes. Attributes (accessors and mutators).
  2. Working with strings and arrays. Search and replace substrings, etc. Type conversion.
  3. Working with files.
  4. Working with the system environment.
  5. Application design, working with gems (modules).
  6. Working with the database.
  7. Installing Ruby on Rails, .

In this post I will publish my first application in Ruby and invite everyone to the discussion. Point out mistakes, suggest best practices, ask questions.

Let's learn Ruby together!

Lesson 1. First application in Ruby.

The task is like this. There is a DNS server on hosting and when calling the console utility in ruby, you need to add a zone for the domain as well as a zone entry in the list of zones (domains.list) and change one entry in the database where to register this domain. Database access settings are stored in the php application, and specifically in its INI file. After all the steps, you need to reboot the DNS server (bind).

Workbench for Ruby

I will use RubyMine from JetBrains as an IDE. I really liked them. Even though it was about phpStorm, the quality is immediately visible. We install Ruby via RVM first for all users, then we configure it for root and our user.

Extending Ruby Public Classes

To work with INI files in Ruby, we use the inifile gem. But there is a small problem with it. In the ZF INI file, you can safely use constants, and the lines will look like this:

IncludePaths = APPLICATION_PATH "/../vendors/Doctrine/"

It’s APPLICATION_INI that blows the gem parser. Specifically, this line does not fit any pattern:

@rgxp_comment = %r/\A\s*\z|\A\s*[#(@comment)]/ @rgxp_section = %r/\A\s*\[([^\]]+)\] /o @rgxp_param = %r/\A([^#(@param)]+)#(@param)\s*"?([^"]*)"?\z/

This is the situation for using public classes. Let's replace the IniFile::parse function with our own. I will put all the additions into the file fucntion.rb

Class IniFile private # # call-seq # parse # # Parse the ini file contents. # def parse return unless File.file?(@fn) section = nil tmp_value = "" tmp_param = "" fd = (RUBY_VERSION >= "1.9" && @encoding) ? File.open(@fn, "r", :encoding => @encoding) : File.open(@fn, "r") while line = fd.gets line = line.chomp # mutline start # create tmp variables to indicate that a multine has started # and the next lines of the ini file will be checked # against the other mutline rgxps. if line =~ @rgxp_multiline_start then tmp_param = $1.strip tmp_value = $2 + "\n" # the mutline end-delimiter is found # clear the tmp vars and add the param / value pair to the section elsif line =~ @rgxp_multiline_end && tmp_param != "" then section = tmp_value + $1 tmp_value, tmp_param = "", "" # anything else between multiline start and end elsif line =~ @rgxp_multiline_value && tmp_param != "" then tmp_value += $1 + "\n" # ignore blank lines and comment lines elsif line =~ @rgxp_comment then next # this is a section declaration elsif line =~ @rgxp_section then section = @ini[$1.strip] # otherwise we have a parameter elsif line =~ @rgxp_param then begin section[$1.strip] = $2.strip rescue NoMethodError raise Error, "parameter encountered before first section" end elsif line =~ %r/APPLICATION_/ then next else raise Error, "could not parse line "#(line)" end end # while ensure fd.close if defined fd and fd end end

I'll also extend the String class to allow domain validation.

Class String def valid_domain_name? domain_name = self.split(".") name = /(?:+)+/.match(domain_name).nil? tld = /(?:(2)|aero|ag|asia|at|be|biz|ca|cc|cn|com|de|edu|eu|fm|gov|gs|jobs|jp|in|info| me|mil|mobi|museum|ms|name|net|nu|nz|org|tc|tw|tv|uk|us|vg|ws)/.match(domain_name).nil? (domain_name.count > 1 and name != false and tld != false) end end

Sources

Well, now I’ll show you the actual sources.
index.rb

#coding: utf-8 require "mysql2" require "socket" require "inifile" require "./functions.rb" # Hash of server machine addresses hosts = ( :production => "83.168.22.1", :test => "84.22 .11.1" ) util = Util.new(hosts) util.releative_config_path="/site.com/application/config/application.ini" # Checking parameters quit if (ARGV.count != 2) domain = ARGV hostname = ARGV. split(".") quit("Invalid domain name") if (not domain.valid_domain_name?) # Search for a company in the database result = Mysql2::Client.new(util.get_db_settings).query("SELECT id FROM `sites` WHERE `hostname` = "#(hostname)"") quit("Company not found") if result.count != 1 # Update its hostname rows = Array.new result.each(|row| rows<< row} company_id = rows["id"] result = Mysql2::Client.new(util.get_db_settings).query("UPDATE `dbname`.`sites` SET `domain` = "#{domain}" WHERE `dao_companies`.`id` =#{company_id};") # Добавление зоны bind_config_path = "/etc/bind" default_zone_file = bind_config_path + "/zones/DEFALT" new_zone_file = bind_config_path + "/zones/#{domain}.zone" zones_list_file = bind_config_path + "/domains.lst" quit("File with default zone does not exists") unless File.exist?(default_zone_file) quit("File with zones list does not exists") unless File.exist?(zones_list_file) zone = IO.read(default_zone_file).gsub("SERIAL",Time.now.strftime("%Y%m%d%S")).gsub("DOMAIN", domain) if not File.exist?(new_zone_file) then File.open(new_zone_file, "w") {|f| f.puts(zone) } else quit("Domain "+domain+" zone already exists!") end # Добавление зоны в список zone = "zone \"#{domain}\" { type master; file \"/etc/bind/zones/#{domain}.zone\"; };" if not IO.read(zones_list_file).include?(domain) then File.open(zones_list_file, "a") {|f| f.puts(zone) } end # Перезапуск сервисов (bind9) system("service bind9 restart") puts "Completed"

Gemfile
This file describes the project's dependencies.

Source:rubygems gem "mysql2", "0.2.6" gem "inifile"

Well, and the actual included functions.
functions.rb

#coding: utf-8 class String def valid_domain_name? domain_name = self.split(".") name = /(?:+)+/.match(domain_name).nil? tld = /(?:(2)|aero|ag|asia|at|be|biz|ca|cc|cn|com|de|edu|eu|fm|gov|gs|jobs|jp|in|info| me|mil|mobi|museum|ms|name|net|nu|nz|org|tc|tw|tv|uk|us|vg|ws)/.match(domain_name).nil? (domain_name.count > 1 and name != false and tld != false) end end class IniFile private # # call-seq # parse # # Parse the ini file contents. # def parse return unless File.file?(@fn) section = nil tmp_value = "" tmp_param = "" fd = (RUBY_VERSION >= "1.9" && @encoding) ? File.open(@fn, "r", :encoding => @encoding) : File.open(@fn, "r") while line = fd.gets line = line.chomp # mutline start # create tmp variables to indicate that a multine has started # and the next lines of the ini file will be checked # against the other mutline rgxps. if line =~ @rgxp_multiline_start then tmp_param = $1.strip tmp_value = $2 + "\n" # the mutline end-delimiter is found # clear the tmp vars and add the param / value pair to the section elsif line =~ @rgxp_multiline_end && tmp_param != "" then section = tmp_value + $1 tmp_value, tmp_param = "", "" # anything else between multiline start and end elsif line =~ @rgxp_multiline_value && tmp_param != "" then tmp_value += $1 + "\n" # ignore blank lines and comment lines elsif line =~ @rgxp_comment then next # this is a section declaration elsif line =~ @rgxp_section then section = @ini[$1.strip] # otherwise we have a parameter elsif line =~ @rgxp_param then begin section[$1.strip] = $2.strip rescue NoMethodError raise Error, "parameter encountered before first section" end elsif line =~ %r/APPLICATION_/ then next else raise Error, "could not parse line "#(line)" end end # while ensure fd.close if defined fd and fd end end def quit(message=nil) banner = " ======================= ==== | DNS Addition tool | ============================ Usage: ruby ​​./index.rb domain.com olddomain.site.com" if not message.nil ? then banner = message end puts banner exit end class Util attr_accessor:hosts, :releative_config_path, :environment def initialize(hosts =Array.new) self.hosts = hosts end # Get local IP address def local_ip orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily UDPSocket.open do |s| s.connect "64.233.187.99", 1 s.addr.last end ensure Socket.do_not_reverse_lookup = orig end # Getting the environment def get_environment if @ environment.nil? then hosts = self.hosts.invert if(hosts.include?(self.local_ip)) then @environment = hosts else @environment = "development" end else @environment.to_s end end def get_config_path local_username = get_local_username "/home/" +local_username+"/sandbox"+self.releative_config_path end # Returns the username if the utility is launched via rvmsudo or directly def get_local_username if ENV["SUDO_USER"].nil? quit("Util should be run over rmvsudo, \r\nexample: rvmsudo ruby ​​./index.rb domain.ru some.subdomain.ru") else ENV["SUDO_USER"] end end def get_db_settings config = IniFile::load( self.get_config_path) section_name = self.get_environment.to_s + " : bootstrap" quit("No suitable section in config file") unless config.has_section?(section_name) dsn = config.to_h["resources.doctrinedata.connections.default. dsn"] # Parse dsn dsn.sub!("mysql://", "") arr = dsn.split("@") dbconfig = ( :username => arr.split(":"), :password = > arr.split(":"), :host => arr.split("/"), :database => arr.split("/") ) end end

What about PHP?

This post is not about quitting PHP and starting learning Ruby. PHP is the most popular web programming language; thousands of interesting things and algorithms are implemented in it, incl. even neural networks. And I love him) Over the years, one can say that I have become close to him, despite all his shortcomings. But this does not mean that you do not need to learn something new for yourself.

Lately I have been asked the question of which books to learn Ruby from. I'm reading this one now.

This book is the official guide to the dynamic programming language Ruby. The team of authors is truly stellar: David Flanagan is a renowned expert in the field of programming, author of a number of best-selling books on JavaScript and Java; Yukihiro "Matz" Matsumoto is the creator and lead developer of Ruby.
The book provides a detailed description of all aspects of the language: the lexical and syntactic structure of Ruby, types of data and elementary expressions, definitions of methods, classes and modules. In addition, the book contains information about the API functions of the Ruby platform.

The publication will be of interest to experienced programmers who are getting acquainted with the new Ruby language, as well as those who already program in Ruby and want to achieve a higher level of understanding and mastery of the work. You can find the book on ozone or biblioglobus.

I look forward to your comments on the code and any interesting ideas!)

Thank you!

If this article helped you, or you want to support my research and blog, here is the best way to do so:

Ruby is a powerful and popular programming language. In addition to its popularity, it is the basis for a well-known framework that allows you to create cool and dynamic websites on various topics. If you look at the TIOBE rating, the language is one of the twenty most popular languages ​​in the world.

The language appeared in 1995 and is considered a young language in comparison with C or C++, which appeared in 1972 and 1983, respectively. The language has a number of advantages and specific features that are implemented exclusively in it, if we compare other popular programming languages.

Course plan

During the video course, you will learn the Ruby language without using additional frameworks. Additional courses on Ruby you can find it at .

During the course we will learn how to install and work with the language, we will study the syntax Ruby(variables, loops, conditional statements), as well as more complex things: OOP, working with files, exceptions, methods, and we will touch on many other topics.


Installing Ruby on Windows

To install Ruby on Windows use RubyInstaller, which can be downloaded from the official website using this link. Download the latest version and install it like a regular program. After the installation is complete, you will see a similar window:

In this window, make sure that the checkbox is checked, then another application will open for installation Ruby into the system.

In the window that opens, enter 1 one by one and press Enter, wait until the installation is complete, press 2 and Enter, and at the end execute the third command by pressing 3 and Enter.

Installing Ruby on Mac

On a Mac, Ruby is installed by default, so you don't need to do anything extra. You can check the language version in the terminal using the following command:

If the version is outdated, you can download a new one. First, you need to download the Ruby version manager. This is done through the terminal using the command:

Curl -L https://get.rvm.io | bash -s stable

After installing the manager, you must restart the terminal. Run the following command:

Rvm list known

After restarting, you can install the version you want. In our case, version 2.4.2 was installed:

Rvm install ruby-2.4.2

At the end, you can check the version again and if it is still old, then simply install the new version by default.

Often Ruby courses are inseparable from Ruby on Rails courses because they are too close to each other. All such training programs are focused on effective and simple development of web applications. Ruby on Rails applications can be ordinary websites, as well as multifunctional social networks and online stores.

Ruby language courses focus on learning the syntax, data types, and main libraries. Knowledge of the language is the basis for completing the Ruby on Rails training program.

Training for the Ruby on Rails framework includes all the steps of building an application - from proper installation to the final work in the form of your own web application.

After training you will be able to

  • create applications in the Ruby programming language;
  • write programs based on OOP principles;
  • use the MVC design pattern in your work;
  • build interaction between the web server and application;
  • automated code testing
  • develop in the Ruby on Rails framework
  • use popular plugins and gems for Ruby on Rails so as not to create your own code from scratch

For whom

To successfully master the course program, you must have programming skills in any language, have an understanding of HTML markup and working with the MySQL DBMS. For basic training in the Ruby language, programming skills are not required, you only need experience with a PC.

Certificates of completion

All training centers issue certificates of completion of courses. The type of certificate depends on the training center, but only the resulting skills matter to the employer.

© 2024 hecc.ru - Computer technology news