1 / 30

Rails Basics

Rails Basics. Ruby on Rails - Rake. Rake is a utility similar to make in Unix. You can say Rake is the make of ruby - the R uby m AKE . Rails defines a number of tasks to help you. Here is a list of various important commands supported by Rake:

vpadilla
Télécharger la présentation

Rails Basics

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Rails Basics

  2. Ruby on Rails - Rake Rake is a utility similar to make in Unix. You can say Rake is the make of ruby - the R uby m AKE. Rails defines a number of tasks to help you. Here is a list of various important commands supported by Rake: * rake db:fixtures:load - Load fixtures into the current environment's database. Load specific fixtures using FIXTURES=x,y * rake db:migrate - Migrate the database through scripts in db/migrate. Target specific version with VERSION=x * rake db:schema:dump - Create a db/schema.rb file that can be portably used against any DB supported by AR. * rake db:schema:load - Load a schema.rb file into the database. * rake db:sessions:clear - Clear the sessions table. * rake db:sessions:create - Creates a sessions table for use with CGI::Session::ActiveRecordStore. * rake db:structure:dump - Dump the database structure to a SQL file. * rake db:test:clone - Recreate the test database from the current environment's database schema. * rake db:test:clone_structure - Recreate the test databases from the development structure. * rake db:test:prepare - Prepare the test database and load the schema. * rake db:test:purge - Empty the test database. * rake doc:appBuild the app HTML Files. * rake doc:clobber_app - Remove rdoc products. * rake doc:clobber_plugins - Remove plugin documentation. * rake doc:clobber_rails Remove rdoc products. * rake doc:plugins - Generate documation for all installed plugins.

  3. Ruby on Rails - Rake # rake doc:rails - Build the rails HTML Files. # rake doc:reapp - Force a rebuild of the RDOC files # rake doc:rerails - Force a rebuild of the RDOC files # rake log:clear - Truncates all *.log files in log/ to zero bytes # rake rails:freeze:edge - Lock this application to latest Edge Rails. Lock a specific revision with REVISION=X. # rake rails:freeze:gems - Lock this application to the current gems (by unpacking them into vendor/rails) # rake rails:unfreeze - Unlock this application from freeze of gems or edge and return to a fluid use of system gems # rake rails:update - Update both scripts and public/javascripts from Rails. # rake rails:update:javascripts - Update your javascripts from your current rails install. # rake rails:update:scripts - Add new scripts to the application script/ directory. # rake stats - Report code statistics (KLOCs, etc) from the application. # rake test - Test all units and functionals # rake test:functionals - Run tests for functionalsdb:test:prepare # rake test:integration - Run tests for integrationdb:test:prepare # rake test:plugins - Run tests for pluginsenvironment # rake test:recent - Run tests for recentdb:test:prepare # rake test:uncommitted - Run tests for uncommitteddb:test:prepare # rake test:units - Run tests for unitsdb:test:prepare # rake tmp:cache:clear - Clears all files and directories in tmp/cache # rake tmp:clear - Clear session, cache, and socket files from tmp/ # rake tmp:create - Creates tmp directories for sessions, cache, and sockets # rake tmp:sessions:clear - Clears all files in tmp/sessions # rake tmp:sockets:clear - Clears all ruby_sess.* files in tmp/sessions

  4. Ruby on Rails - Controller methods Each public method in a controller is callable by the (standard) URL scheme /controller/action class WorldController < ApplicationController def hello render :text => 'Hello world' end Parameters are stored in the params hash: /world/hello/1?foo=bar id = params[:id] # 1 foo = params[:foo] # bar Instance variables defined in the the controllers methods are available to the corresponding view templates: def show @person = Person.find( params[:id]) end

  5. Ruby on Rails - Render Usually the view template with the same name as the controller method is used to render the results. Action: # The default. Does not need to be specified # in a controller method called "some_action" render :action => 'some_action' render :action => 'another_action', :layout => false render :action => 'some_action', :layout => 'another_layout' Template: Like rendering an action, but finds the template based on the template root (app/views) # renders app/views/weblog/show render :template => 'weblog/show' File: render :file => '/path/to/some/file.rhtml' render :file => '/path/to/some/filenotfound.rhtml', status => 404, :layout => true Text: render :text => "Hello World" render :text => "This is an error", :status => 500 render :text => "Let's use a layout", :layout => true render :text => 'Specific layout', :layout => 'special'

  6. Ruby on Rails - Render Inline Template: Uses ERb to render the "miniature" template render :inline => "<%= 'hello' %>" Nothing: render :nothing render :nothing, :status => 403 # forbidden

  7. Ruby on Rails - HTML Forms Form: To create a form tag with the specified action, and with POST request, use the following syntax: <%= form_tag :action => 'update', :id => @some_object %> <%= form_tag( { :action => :save, }, { :method => :post }) %> Use :multipart => true to define a MIME-multipart form (for file uploads). <%= form_tag( {:action => 'upload'}, :multipart => true ) %> File Upload: Define a multipart form in your view: <%= form_tag( { :action => 'upload' }, :multipart => true ) %> Upload file: <%= file_field( "form", "file" ) %> <br /> <%= submit_tag( "Upload file" ) %> <%= end_form_tag %> Handle the upload in the controller: def upload file_field = @params['form']['file'] rescue nil # file_field is a StringIO object file_field.content_type # 'text/csv' file_field.full_original_filename ... end

  8. Ruby on Rails – Input Helpers Text Fields: To create a text field use the following syntax: <%= text_field :modelname, :attribute_name, options %> Example: <%= text_field "person", "name", "size" => 20 %> This will generate following code: <input type="text" id="person_name" name="person[name]" size="20" value="<%= @person.name %>" /> To create hidden fileds use the following syntax; <%= hidden_field ... %> To create password fileds use the following syntax; <%= password_field ... %> To create file upload fileds use the following syntax; <%= file_field ... %> Text Area: To create a text area use the following syantax: <%= text_area ... %>

  9. Ruby on Rails - HTML Forms Have a look at the following example: <%= text_area "post", "body", "cols" => 20, "rows" => 40%> This will generate following code: <textarea cols="20" rows="40" id="post_body" name="post[body]"> <%={@post.body}%> </textarea> Radio Button: To create a Radio Button use the following syantax: <%= radio_button :modelname, :attribute, :tag_value, options %> Example: radio_button("post", "category", "rails") radio_button("post", "category", "java") This will generate following code: <input type="radio" id="post_category" name="post[category]" value="rails" checked="checked" /> <input type="radio" id="post_category" name="post[category]" value="java" />

  10. Ruby on Rails - HTML Forms Checkbox Button: To create a Checkbox Button use the following syantax: <%= check_box :modelname, :attribute,options,on_value,off_value%> Example: check_box("post", "validated") This will generate following code: <input type="checkbox" id="post_validate" name="post[validated]" value="1" checked="checked" /> <input name="post[validated]" type="hidden" value="0" /> Let's check another example: check_box("puppy", "gooddog", {}, "yes", "no") This will generate following code: <input type="checkbox" id="puppy_gooddog" name="puppy[gooddog]" value="yes" /> <input name="puppy[gooddog]" type="hidden" value="no" />

  11. Ruby on Rails - HTML Forms Options: To create a dropdopwn list use the following syntax: <%= select :variable,:attribute,choices,options,html_options%> Have a look at the following example: select("post", "person_id", Person.find(:all).collect {|p| [ p.name, p.id ] }) This could generate following code. It depends on what value is available in your database.: <select name="post[person_id]"> <option value="1">David</option> <option value="2">Sam</option> <option value="3">Tobias</option> </select>

  12. Ruby on Rails - HTML Forms Date Time: Following is the syntax to use data and time: <%= date_select :variable, :attribute, options %> <%= datetime_select :variable, :attribute, options %> Following are examples of usage: <%=date_select "post", "written_on"%> <%=date_select "user", "birthday", :start_year => 1910%> <%=date_select "user", "cc_date", :start_year => 2005, :use_month_numbers => true, :discard_day => true, :order => [:year, :month]%> <%=datetime_select "post", "written_on"%> End Form Tag Use following syntax to create </form> tag: <%= end_form_tag %>

  13. Rails and HTML - RHTML RHTML is HTML mixed with Ruby, using HTML tags. All of Ruby is available for programming alongwith HTML: Following is the syntax of using Ruby with HTML: <% %> # executes the Ruby code <%= %> # executes the Ruby code and displays the result Example: <ul> <% @products.each do |p| %> <li><%= @p.name %></li> <% end %> </ul> The output of anything in <%= %> tags is directly copied to the HTML output stream. To secure against HTML injection, use the h() function to html_escape the output For example:: <%=h @user_entered_notes %>

  14. Rails and HTML Links Following is the quick view on link_to, mail_to. link_to "Name", :controller => 'post', :action => 'show', :id => @book.id link_to "Delete", { :controller => "admin", :action => "delete", :id => @post }, { :class => 'css-class', :id => 'css-id', :confirm => "Are you sure?" } image_tag "spinner.png", :class => "image", :alt => "Spinner" mail_to "info@invisible.ch", "send mail", :subject => "Support request by #{@user.name}", :cc => @user.email, :body => '....', :encoding => "javascript" stylesheet_link_tag "scaffold", "admin", :media => "all"

  15. Ruby on Rails - Session and Cookies Sessions: To save data across multiple requests, you can use either the session or the flash hashes. A flash stores a value (normally text) until the next request, while a session stores data during the complete session. session[:user] = @user flash[:message] = "Data was saved successfully" <%= link_to "login", :action => 'login' unless session[:user] %> <% if flash[:message] %> <div><%= h flash[:message] %></div> <% end %> It's possible to turn off session management: session :off # turn session management off session :off, :only => :action # only for this :action session :off, :except => :action # except for this action

  16. Ruby on Rails - Session and Cookies Cookies: Following is the syntax for setting cookies: # Set a simple session cookie cookies[:user_name] = "david" # Set a cookie that expires in 1 hour cookies[:login] = { :value => "XJ12", :expires => Time.now + 3600} Following is the syntax for reading cookies: cookies[:user_name] # => "david" cookies.size # => 2 Following is the syntax for deleting cookies: cookies.delete :user_name All the option symbols for setting cookies are: * value - the cookie.s value or list of values (as an array). * path - the path for which this cookie applies. Defaults to the root of the application. * domain - the domain for which this cookie applies. * expires - the time at which this cookie expires, as a +Time+ object. * secure - whether this cookie is a secure cookie or not (default to false). Secure cookies are only transmitted to HTTPS servers.

  17. Ruby on Rails - User Input Validations Here is the list of validations which you can perform on user input: validates_presence_of: Following check that last_name and first_name should be filled and should not be NULL. validates_presence_of :firstname, :lastname validates_length_of: Following example shows various validations on a single filed. These validations can be performed separately. validates_length_of :password, :minimum => 8 # more than 8 characters :maximum => 16 # shorter than 16 characters :in => 8..16 # between 8 and 16 characters :too_short => ‘password too short' :too_long => ‘password too long' validates_acceptance_of: Following will accept only 'Y' value for option field. validates_acceptance_of :option :accept => 'Y'

  18. Ruby on Rails - User Input Validations validates_confirmation_of: The fields password and password_confirmation must match and will be used as follows: validates_confirmation_of :password validates_uniqueness_of: Following puts a condition for user_name to be unique. validates_uniqueness_of :user_name validates_format_of: Following validates a that given email ID is in a valid format. This shows how you can use regualr expression to validatea filed. validates_format_of :email :with => /^(+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i validates_numericality_of: This validates that given field is numeric. validates_numericality_of :value :only_integer => true :allow_nil => true validates_inclusion_of: Following checks that passed value is an enumeration and falls in the given range. validates_inclusion_of :gender, :in => %w( m, f )

  19. Ruby on Rails - User Input Validations validates_exclusion_of: Following checks that given values does not fall in the given range. validates_exclusion_of :age :in => 13..19 validates_inclusion_of: Following checks that given values should fall in the given range. This is opposite to validates_exclusion_of. validates_inclusion_of :age :in => 13..19 Options for all Validations: You can use following options alongwith all the validations. * :message => 'my own errormessage' Use this to print a custom error message in case of validation fails. * :on => :create or :update This will be used in such cases where you want to perform validation only when record is being created or updated. So if you use :create then this validation work only when there is a create operation on database.

  20. Ruby on Rails - The Maths Functions Consider a table object called Person. This table is having fields like age, first_name, last_name and salary. Following will return average age of all the employee. Person.average :age Following will return maximum age of the employee. Person.maximum :age Following will return minimum age of the employee. Person.minimum :age Follwoing will return sum of salaries of all the employees. Person.sum :salary, :group => :last_name Following will count the number of records having age more than 26. Person.count(:conditions => "age > 26") Following count total number of records. Person.count

  21. Rails Scaffolds While you're developing Rails applications, especially those which are mainly providing you with a simple interface to data in a database, it can often be useful to use the scaffold method. Scaffolding provides more than cheap demo thrills. Here are some benefits: You can quickly get code in front of your users for feedback. You are motivated by faster success. You can learn how Rails works by looking at generated code. You can use the scaffolding as a foundation to jumpstarts your development. e.g. > rails generate scaffold article

  22. Ruby on Rails - Routing All the information pertaining to which controller and action to call on comes in the form of the request URL. Action Pack includes a specialized component called routing, which is responsible for dissecting the incoming URL and delegating control to the appropriate controller and action. Every request that comes into your web application originates in the form of a URL. The routing system allows you to write the rules that govern how each URL is picked apart and handled.

  23. The Action Pack Request Cycle The entire request-to-response process is called the Action Pack request cycle. The request cycle consists of the following steps: 1. Rails receives a request from the outside world (usually a browser). 2. Routing picks apart the request to determine the controller and action to invoke. 3. A new controller object is instantiated, and an action method is called. 4. The controller interacts with the model (usually performing a CRUD operation). 5. A response is sent back to the browser, in the form of either a render or a redirect.

  24. Routing Basics In Rails, all the rules for mapping URLs to controllers are a matter of configuration. You can find the routes.rb file in the config directory. If you open that file in your editor now and examine it, you see lots of commented code with samples of routes you could possibly define. Look at the last commented line to understand how routes can be defined: match ':controller(/:action(/:id(.:format)))' Routing priority is based on the order in which routes exist in routes.rb, so that the first route defined has the highest priority. If an incoming URL matches the first route defined, the request is sent along, and no other routes are examined. Routes are commonly defined using the match method. The argument to match can either be a string pattern to match, as in the previous example, or a hash with string pattern as a key and another string that identifies the controller and action to be called. Here’s an example that matches a specific pattern and sets the controller and action in response: match '/teams/home' => 'teams#index' This route matches a URL like http://example.com/teams/home and routes the request to the index action on the teams controller. The name of the controller and action are separated by the # symbol. You can also set arbitrary parameters when using the route. For example, let’s say you want to set a parameter called query that you can access and use in your controller: match '/teams/search/:query' => 'teams#search' This route matches a URL like http://example.com/teams/search/toronto, routing the request to the teams controller and the search action. The third segment in the URL is assigned to the :query parameter because you specify :query as an in-line variable.

  25. Named Routes One of the coolest things about routing in Rails is a feature known as named routes. You can assign a name to a given route to make referring to it in code easier. You still define the route the same way as a regular routes, but you need a new hash pair, where the key is :as and the value is the name of the route. For example, let’s take the search route defined in the previous section and turn it into a named route: match '/teams/search/:query' => 'teams#search', :as => 'search' With this definition in place, Rails creates helper methods that allow you to reference this particular route using its name: search_url and search_path. The *_url variant returns a full URL including the protocol and hostname (http://example.com/teams/search), whereas the *_path variant returns just the path (/teams/search). link_to "Search", search_path outputs <a href="/teams/search">Search</a> Named routes are shorter, DRYer, and impervious to changes made at the routing level. So, if you change the controller name from teams to cities, you don’t need to update links that use the named route; for the unnamed version, you do.

  26. RESTful Resources Rails adapted RESTful design as a convention in Rails 1.2 onward. Representational State Transfer (REST) is a principle used mainly over the HTTP protocol to offer a better interface for client-server operations. This section first talks about the REST concept and then explains how Rails implemented it through RESTful controllers and resources. The REST principle is based on working with information in the form of resources. Each piece of information is dealt with as a resource, each resource has a unique interaction point for every action that can be performed on it, and each interaction point (action) is normally represented using a URL and a request method. For example, think of a blog, which is a collection of information resources. Every article is a resource, and every action you perform on it, such as read, edit, or delete, has its own interaction point, mainly identified by a URL and a request method. HTTP protocol, which is the main web protocol you normally use in browsers, has several request methods. These four are the primary ones used in RESTful design: • POST: Normally used to submit forms and new resource data • GET: Mainly used to request a page to view a resource or more • PUT: Used to modify specific resource • DELETE: Used to delete a resource RESTful web services are commonly used in APIs (referred to as REST APIs) by associating every CRUD method with its corresponding HTTP method: • POST/Create: Creates of a resource • GET/Read: Requests a specific resource or group of resources • PUT/Update: Edits attributes of a resource • DELETE/Delete: Deletes a resource

  27. RESTful Routes and Resources Earlier, the discussion of RESTful design said that information is dealt with in the form of resources. Rails makes it easy for you to do that: for every action in your controller, you have an associated named route to call. Resources are configured in the routes.rb file using the resources method. If you look at the routes file in your blog application, you see resources :articles at the top: it was added when you generated the articles scaffold in Chapter 3. The resources :articles method defines the following named routes for the articles controller: article_path => /articles/:id articles_path => /articles edit_article_path => /articles/:id/edit new_article_path => /articles/new The resources method generated four named routes for you; but when you open the ArticlesController, you have seven actions (see Table 6-1). How can you access the remaining actions? Remember that when you learned about REST earlier, you saw that every operation is identified by both a URL and a request method. Using different request methods with the generated named routes, Rails routes them to the appropriate controller actions. By following the REST convention, instead of defining a named route for every action, you use the resources method in your routes file. To give some examples, if you want to access the index action in your articles controller, you go to /articles in your browser; the default request method when you type a URL in your browser is GET. What if you want to create a new article? You can do that by submitting a form to /articles with the default request method for forms, POST. To get a specific article, type /articles/:id, where :id is your article id. It’s that simple. NOTE You can list all the available routes in your application by calling the rake routes command from the terminal.

  28. Rendering Responses When an action has completed, it attempts to render a template of the same name. That’s the case with the index action just discussed: it renders the index.html.erb template by default. The same applies to edit, new and show actions. But sometimes you want to render something else. If you look at the create and update actions, notice that if the @article.save succeeds, you redirect to the saved @article show page with a friendly message. However, if the save fails, you want to render the new or the edit template. If you didn’t explicitly render those templates, the actions would fall through to their default behavior and attempt to render their default create and update templates, which don’t exist. The render method takes several options for its first argument: :text, :nothing, :inline, :template, :action, :xml, :json, :js, and :update. A RESTful controller normally has seven default actions, and in every one of them you do the following: • Set an instance variable to be used later in the rendered action or template • Handle the response using the respond_to method to either do a render or redirect_to another path, depending on the behavior you want to achieve

  29. Redirecting That method is called redirect_to, and it’s one you’ll find yourself using a lot, so it’s a good idea to get familiar with it. The redirect_to method usually takes a URL as a parameter, which in most cases is represented by one of your routes. Let’s say that you want to redirect the user to the articles’ index page, and the path you use is articles_path—a route added by resources :articles in config/routes.rb; so, you execute redirect_to(articles_path). If you look at the destroy action, the user is redirected to articles_url after an article is deleted. As you can see from the create and update actions, redirect_to can also take an object as a parameter, in which case it redirects to a path that represents that object. This means Rails uses a convention to translate objects to their show action named route. In this case, redirect_to(@article) is a shortcut equivalent to redirect_to(article_path(:id => @article)). A RESTful controller normally has seven default actions, and in every one of them you do the following: • Set an instance variable to be used later in the rendered action or template • Handle the response using the respond_to method to either do a render or redirect_to another path, depending on the behavior you want to achieve

  30. Working with Layouts Rails uses layouts to interpolate the output of an individual template into a larger whole—a reversal of the common pattern of including a shared header and footer on every page A template is placed in app/views/layouts/application.html.erb. The application.html.erb layout is applied to all controllers. However, if you like your layout to apply to a specific controller, you can create a layout file named after the controller you want. For example, a layout that applies only to the articles controller should be created in app/views/layouts/articles.html.erb. Just as an action tries to render itself using a view that matches its name, a controller attempts to use a layout that matches its name. Open the app/views/layouts/application.html.erb in your editor. You should see something like the file shown below: <html> <head> <title>Blog</title> <%= stylesheet_link_tag :all %> <%= javascript_include_tag :defaults %> <%= csrf_meta_tag %> </head> <body> <%= yield %> </body> </html> Wherever you put the yield keyword is where your content goes.

More Related