I studied Ruby tutorials, now I want to understand the logic (structure) of the ROR website. In a word, how it all looks.

Could you rewrite this simple PHP code as if it were written in ROR?

// HTML / CSS / JS:

<html> <head>.. <script> function send(){ var xmlhttp = getXmlHttp(); xmlhttp.open('POST', '/send.php', true); xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xmlhttp.send("data=" + $("#test").val() ); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4) if(xmlhttp.status == 200) if(xmlhttp.responseText) alert("Done"); } </script> </head> <body> <input type='text' id='test' /> <button onclick='send()'>OK</button> </body> </html> 

// Send.php

 <?php> $data=$_POST['data']; if($data=='1') echo true; else echo false; </php> 
  • one
    Now study Rails tutorials, and it will immediately become clear. - D-side

1 answer 1

Such simple handlers are much easier to describe in Sinatra :

 require 'sinatra' post '/send' do if params['data'] == '1' 'true' else 'false' end end 

In Sinatra, the answer is the value that the block (from do to end ) returned. In this case, the answers are just strings. In Ruby, there is an "implicit return of the last expression", and the values ​​return almost everything. if we are interested in here, for example, it returns the value returned by the executed branch.

Unlike PHP, which handler (that is, the code frargment) will be involved in the request, does not depend on the location of the code file in the file system. The criteria are described right next to the code of the HTTP handlers themselves (HTTP endpoint). Here it defines a post '/send' , imposing restrictions on the method ( POST ) and path (exact match with /send ).


In Rails, if we exclude the template code from rails new , the logic itself will be located in the controller class:

app/controllers/sample_controller.rb

 class SampleController < ApplicationController def send if params['data'] == '1' render text: 'true' else render text: 'false' end end end 

... and since the routing system does not rely on the file system, you need to specify in the route file which requests will be sent to this method:

config/routes.rb

 post '/send', to: 'sample#send' 

It seems that in Sinatra, only the handler is passed not by the immediate value (do.end block), but in the format контроллер#действие ( controller#action ), and in addition to additional criteria (dynamic segments, criteria for parameters, headers) performed differently. In general, the easiest way is not to draw parallels between them, but to look at these two systems separately.

In an amicable way, there could still be a model class , but it is needed only to separate the response mechanism (in the controller) from the problem being solved (in the model), which is trivial here.