Rails is a web application framework written in Ruby that makes programming web applications easier. The key principles of Rails are DRY (Don't Repeat Yourself), convention over configuration, and using RESTful architecture. Rails uses the MVC pattern with models representing data, views representing the user interface, and controllers handling requests and passing data between models and views. Creating a Rails application involves generating the app, setting up the database schema through migrations, and using validations and callbacks to control object state changes.
The document discusses setting up a Ruby on Rails web application. It explains how to install Ruby and Rails, configure the database, and generate models. The Rails directory structure is described, including the app, config, and db folders. Finally, it shows how to start the web server and create a basic Rails application.
Meetup developing building and_deploying databases with SSDTSolidify
This document discusses concepts, development, build, and release processes for databases using SQL Server Data Tools (SSDT) and the Data-Tier Application Framework (DACFx). It covers importing databases into SSDT projects, refactoring, using pre-deployment and post-deployment scripts, building DacPacs, continuous integration, and deploying DacPacs during a release. The goal is to manage database changes and deployments in a consistent, repeatable manner from development to production.
A detailed overview of the laravel framework, created by Awulonu Obinna and presented at: Laravel Abuja.
Author details:
Twitter – https://www.twitter.com/awulonu_obinna
Facebook – https://www.facebook.com/awulonuobinna
GitHub – https://www.github.com/obinosteve
This document provides an overview of Ruby on Rails, a web application framework written in Ruby. It discusses what Ruby and Rails are, the key strengths of Rails like productivity and convention over configuration. It then demonstrates how to build a basic Rails application, including generating models and controllers, scaffolding, and adding relationships between models. The document aims to introduce developers to Ruby on Rails and demonstrate its capabilities.
This document provides an overview of the Laravel PHP framework, including instructions for installation, directory structure, MVC concepts, and a sample "task list" application to demonstrate basic Laravel features. The summary covers creating a Laravel project, defining a database migration and Eloquent model, adding routes and views with Blade templating, performing validation and CRUD operations, and more.
The document discusses setting up a Ruby on Rails web application. It explains how to install Ruby and Rails, configure the database, and generate models. The Rails directory structure is described, including the app, config, and db folders. Finally, it shows how to start the web server and create a basic Rails application.
Meetup developing building and_deploying databases with SSDTSolidify
This document discusses concepts, development, build, and release processes for databases using SQL Server Data Tools (SSDT) and the Data-Tier Application Framework (DACFx). It covers importing databases into SSDT projects, refactoring, using pre-deployment and post-deployment scripts, building DacPacs, continuous integration, and deploying DacPacs during a release. The goal is to manage database changes and deployments in a consistent, repeatable manner from development to production.
A detailed overview of the laravel framework, created by Awulonu Obinna and presented at: Laravel Abuja.
Author details:
Twitter – https://www.twitter.com/awulonu_obinna
Facebook – https://www.facebook.com/awulonuobinna
GitHub – https://www.github.com/obinosteve
This document provides an overview of Ruby on Rails, a web application framework written in Ruby. It discusses what Ruby and Rails are, the key strengths of Rails like productivity and convention over configuration. It then demonstrates how to build a basic Rails application, including generating models and controllers, scaffolding, and adding relationships between models. The document aims to introduce developers to Ruby on Rails and demonstrate its capabilities.
This document provides an overview of the Laravel PHP framework, including instructions for installation, directory structure, MVC concepts, and a sample "task list" application to demonstrate basic Laravel features. The summary covers creating a Laravel project, defining a database migration and Eloquent model, adding routes and views with Blade templating, performing validation and CRUD operations, and more.
This document discusses new features in SQL Server including MERGE statements, table valued parameters, grouping sets, and FILESTREAM storage. MERGE statements allow inserting, updating, and deleting data in one statement based on matching or non-matching rows between two tables. Table valued parameters allow passing tables of data as parameters to stored procedures. Grouping sets enable grouping data by multiple columns in a single query. FILESTREAM storage integrates the database engine with the file system to allow storing large binary objects on disk for improved performance.
Net-a-Porter has embarked on the mission of separating database refactoring from code deployment. The solution we've come up with is "refactoring as a service" and a soon-to-be released Perl module which drives it.
I'll explain how Liquibase, our Git repositories, Puppet and Jenkins all fit together to make database refactoring easy and deployment safe and roll-backable.
I'll also tell you how I just discovered Sqitch as a possible replacement for Liquibase.
... and all within 20 minutes!
Project Fedena and Why Ruby on Rails - ArvindArvind G SThoughtWorks
Project Fedena is an open source school management system built using Ruby on Rails. It was developed by Foradian Technologies in response to requests from schools in India needing an efficient data management solution. The project started with two developers learning Ruby and Rails simultaneously with building the initial application. Key aspects of the system include its user-friendly interface, ease of use, and architectural design using Rails, MySQL database, and other plugins. While Rails provided benefits like code readability and conventions, ongoing work is focused on improvements to testing, deployment, performance, and scalability. The project aims to develop an open community of contributors on its website at ProjectFedena.org.
In this presentation we will examine various scalability options in order to improve the robustness and performance of your Spring Batch applications. We start out with a single threaded Spring Batch application that we will refactor so we can demonstrate how to run it using:
* Concurrent Steps
* Remote Chunking
* AsyncItemProcessor and AsyncItemWriter
* Remote Partitioning
Additionally, we will show how you can deploy Spring Batch applications to Spring XD which provides high availability and failover capabilities. Spring XD also allows you to integrate Spring Batch applications with other Big Data processing needs.
Directory Structure Changes in Laravel 5.3DHRUV NATH
Now Laravel Developer will experience new design which has already covered the fresh routes directory and a latest directory change coming many of the default folders will not show up until you run a command that needs them.
This document summarizes the directory structure of a Laravel project called "demo" that was created using Composer. It contains the core code in the app directory, configuration files in config, database migrations and models in database, public assets in public, views and language files in resources, route definitions in routes, storage in storage, tests in tests, and vendor dependencies in vendor. The document provides brief descriptions of the purpose of each main directory.
This document summarizes Jennifer McNeill's presentation on converting Oracle Reports to BI Publisher. It discusses the challenges of enterprise reporting, benefits of using BI Publisher like simplified report maintenance and flexible output formats. It provides a step-by-step approach to conversion including using the conversion utility, integrating Oracle Forms with BI Publisher, and challenges of a conversion project.
This document provides an overview of REST and JAX-RS. It defines REST as an architectural style using HTTP for data communication. Key REST fundamentals are discussed such as resources with unique IDs, standard HTTP methods, and hyperlinks to relate resources. The Richardson Maturity Model for REST APIs is introduced with levels ranging from using HTTP as a simple transport to fully leveraging hypermedia. JAX-RS is defined as a Java annotation-based framework for developing RESTful web services, with annotations explained for defining resources, request parameters, responses, and error handling. The document also covers REST concepts like pagination, authentication, and linking resources.
An AMIS Overview of Oracle database 12c (12.1)Marco Gralike
Presentation used by Lucas Jellema and Marco Gralike during the AMIS Oracle Database 12c Launch event on Monday the 15th of July 2013 (much thanks to Tom Kyte, Oracle, for being allowed to use some of his material)
M.
2012.10 Liferay Europe Symposium, Alistair OldfieldEmeldi Group
This document outlines the approach and execution of migrating a Microsoft SharePoint site into Liferay. It describes inspecting the SharePoint environment and exporting content like pages, documents, and images into XML packages. Custom SharePoint web parts are reimplemented as Java portlets in Liferay. During import, URLs are rewritten and markup is filtered to replace links to the original SharePoint site. The automated, repeatable process allows full migration of content while reusing ported applications in new Liferay installations.
This presentation about common problems with data base versioning, migration and maintaining during project live cycle. Also we will look at useful tools that can help us to solve these problems. Then we will compare two most popular tools Liquibase and Flyway , and run live demo with small migration using one of them.
LiquiBase is an open source tool for tracking, managing and applying database changes, where database changes are stored in an XML file called a changelog that is executed to handle different revisions. It aims to provide consistent database changes across environments by managing databases at different states and keeping a history of all changes made through automatic rollback support and ability to effectively manage variable changes. Problems with manual database changes include inconsistent application of changes and databases becoming out of sync between environments.
JavaEE and RESTful development - WSO2 Colombo Meetup Sagara Gunathunga
This document discusses RESTful development and JavaEE concepts. It begins with an introduction to REST and provides an example to distinguish RESTful and non-RESTful architectures. It then covers JavaEE topics like JAX-RS, dependency injection, and integrating JAX-RS services with JPA DAO services using CDI. The document also describes features of the WSO2 Application Server like multi-tenancy support, multiple classloading runtimes, and monitoring capabilities.
Continuous DB Changes Delivery With LiquibaseAidas Dragūnas
The short overview of Continuous Delivery process. The overview of Liquibase technology as one of open source technologies, designed for DB changes migration. Live demonstration of how Liquibase could be used in Continuous Delivery process.
This document outlines an approach for migrating content and functionality from a Microsoft SharePoint site into Liferay. It describes exporting SharePoint pages, libraries, and web parts into XML packages, then importing them into Liferay using custom importers. Web part functionality is reimplemented as Java portlets, and SharePoint URLs in content are rewritten during import. The automated, repeatable process allows full migration of a SharePoint site structure and content into Liferay.
This document discusses using the Flyway tool to manage database schema migrations. Flyway allows defining SQL scripts to update the database schema and records the changes in a schema version table. The document provides instructions on setting up Flyway for a project, running migrations with Flyway, and the process for adding new migrations when making changes to data models.
This document provides an overview of CodeIgniter and the Model-View-Controller (MVC) framework. It discusses the key features supported by CodeIgniter including database classes, validation, security filtering, and more. It explains the basic MVC structure with models representing data, views representing presented information, and controllers serving as intermediaries. The document demonstrates how CodeIgniter handles URLs in a segment-based approach and describes the roles of controllers, views, models, helpers, libraries, and hooks within a CodeIgniter application. Code examples are provided to illustrate how each component works.
Atlanta JUG - Integrating Spring Batch and Spring IntegrationGunnar Hillert
This document provides an overview and introduction to Spring Batch, Spring Integration, and Spring XD. It discusses key concepts and features of Spring Batch for batch processing and Spring Integration for enterprise integration. It also demonstrates how Spring Batch and Spring Integration can be used together for batch integration use cases. Finally, it introduces Spring XD for unified data ingestion, analytics, and export capabilities using existing Spring projects. The presentation includes code samples and links to documentation and GitHub repositories for further information.
Ruby on Rails is an open-source web application framework that uses the Model-View-Controller pattern. It uses Ruby as its programming language. Rails provides conventions for building database-backed web applications, including generating scaffolding for basic CRUD operations. The document demonstrates how to generate a Rails application, scaffold a Bookmarks model, add validations and associations to Categories, and integrate Ajax functionality. Rails emphasizes conventions over configuration for directory structure and default actions.
Ruby on Rails is an open-source web application framework that uses the Model-View-Controller pattern. It uses Ruby as its programming language. Rails provides conventions for building database-backed web applications, including scaffolding that automatically generates the basic structure and files needed for a model. Rails emphasizes conventions over configuration, including naming conventions and default directory structures. The document provides an overview of Rails and demonstrates how to generate a sample bookmarks application using Rails, including generating models, views, controllers, and associations between models.
This document discusses new features in SQL Server including MERGE statements, table valued parameters, grouping sets, and FILESTREAM storage. MERGE statements allow inserting, updating, and deleting data in one statement based on matching or non-matching rows between two tables. Table valued parameters allow passing tables of data as parameters to stored procedures. Grouping sets enable grouping data by multiple columns in a single query. FILESTREAM storage integrates the database engine with the file system to allow storing large binary objects on disk for improved performance.
Net-a-Porter has embarked on the mission of separating database refactoring from code deployment. The solution we've come up with is "refactoring as a service" and a soon-to-be released Perl module which drives it.
I'll explain how Liquibase, our Git repositories, Puppet and Jenkins all fit together to make database refactoring easy and deployment safe and roll-backable.
I'll also tell you how I just discovered Sqitch as a possible replacement for Liquibase.
... and all within 20 minutes!
Project Fedena and Why Ruby on Rails - ArvindArvind G SThoughtWorks
Project Fedena is an open source school management system built using Ruby on Rails. It was developed by Foradian Technologies in response to requests from schools in India needing an efficient data management solution. The project started with two developers learning Ruby and Rails simultaneously with building the initial application. Key aspects of the system include its user-friendly interface, ease of use, and architectural design using Rails, MySQL database, and other plugins. While Rails provided benefits like code readability and conventions, ongoing work is focused on improvements to testing, deployment, performance, and scalability. The project aims to develop an open community of contributors on its website at ProjectFedena.org.
In this presentation we will examine various scalability options in order to improve the robustness and performance of your Spring Batch applications. We start out with a single threaded Spring Batch application that we will refactor so we can demonstrate how to run it using:
* Concurrent Steps
* Remote Chunking
* AsyncItemProcessor and AsyncItemWriter
* Remote Partitioning
Additionally, we will show how you can deploy Spring Batch applications to Spring XD which provides high availability and failover capabilities. Spring XD also allows you to integrate Spring Batch applications with other Big Data processing needs.
Directory Structure Changes in Laravel 5.3DHRUV NATH
Now Laravel Developer will experience new design which has already covered the fresh routes directory and a latest directory change coming many of the default folders will not show up until you run a command that needs them.
This document summarizes the directory structure of a Laravel project called "demo" that was created using Composer. It contains the core code in the app directory, configuration files in config, database migrations and models in database, public assets in public, views and language files in resources, route definitions in routes, storage in storage, tests in tests, and vendor dependencies in vendor. The document provides brief descriptions of the purpose of each main directory.
This document summarizes Jennifer McNeill's presentation on converting Oracle Reports to BI Publisher. It discusses the challenges of enterprise reporting, benefits of using BI Publisher like simplified report maintenance and flexible output formats. It provides a step-by-step approach to conversion including using the conversion utility, integrating Oracle Forms with BI Publisher, and challenges of a conversion project.
This document provides an overview of REST and JAX-RS. It defines REST as an architectural style using HTTP for data communication. Key REST fundamentals are discussed such as resources with unique IDs, standard HTTP methods, and hyperlinks to relate resources. The Richardson Maturity Model for REST APIs is introduced with levels ranging from using HTTP as a simple transport to fully leveraging hypermedia. JAX-RS is defined as a Java annotation-based framework for developing RESTful web services, with annotations explained for defining resources, request parameters, responses, and error handling. The document also covers REST concepts like pagination, authentication, and linking resources.
An AMIS Overview of Oracle database 12c (12.1)Marco Gralike
Presentation used by Lucas Jellema and Marco Gralike during the AMIS Oracle Database 12c Launch event on Monday the 15th of July 2013 (much thanks to Tom Kyte, Oracle, for being allowed to use some of his material)
M.
2012.10 Liferay Europe Symposium, Alistair OldfieldEmeldi Group
This document outlines the approach and execution of migrating a Microsoft SharePoint site into Liferay. It describes inspecting the SharePoint environment and exporting content like pages, documents, and images into XML packages. Custom SharePoint web parts are reimplemented as Java portlets in Liferay. During import, URLs are rewritten and markup is filtered to replace links to the original SharePoint site. The automated, repeatable process allows full migration of content while reusing ported applications in new Liferay installations.
This presentation about common problems with data base versioning, migration and maintaining during project live cycle. Also we will look at useful tools that can help us to solve these problems. Then we will compare two most popular tools Liquibase and Flyway , and run live demo with small migration using one of them.
LiquiBase is an open source tool for tracking, managing and applying database changes, where database changes are stored in an XML file called a changelog that is executed to handle different revisions. It aims to provide consistent database changes across environments by managing databases at different states and keeping a history of all changes made through automatic rollback support and ability to effectively manage variable changes. Problems with manual database changes include inconsistent application of changes and databases becoming out of sync between environments.
JavaEE and RESTful development - WSO2 Colombo Meetup Sagara Gunathunga
This document discusses RESTful development and JavaEE concepts. It begins with an introduction to REST and provides an example to distinguish RESTful and non-RESTful architectures. It then covers JavaEE topics like JAX-RS, dependency injection, and integrating JAX-RS services with JPA DAO services using CDI. The document also describes features of the WSO2 Application Server like multi-tenancy support, multiple classloading runtimes, and monitoring capabilities.
Continuous DB Changes Delivery With LiquibaseAidas Dragūnas
The short overview of Continuous Delivery process. The overview of Liquibase technology as one of open source technologies, designed for DB changes migration. Live demonstration of how Liquibase could be used in Continuous Delivery process.
This document outlines an approach for migrating content and functionality from a Microsoft SharePoint site into Liferay. It describes exporting SharePoint pages, libraries, and web parts into XML packages, then importing them into Liferay using custom importers. Web part functionality is reimplemented as Java portlets, and SharePoint URLs in content are rewritten during import. The automated, repeatable process allows full migration of a SharePoint site structure and content into Liferay.
This document discusses using the Flyway tool to manage database schema migrations. Flyway allows defining SQL scripts to update the database schema and records the changes in a schema version table. The document provides instructions on setting up Flyway for a project, running migrations with Flyway, and the process for adding new migrations when making changes to data models.
This document provides an overview of CodeIgniter and the Model-View-Controller (MVC) framework. It discusses the key features supported by CodeIgniter including database classes, validation, security filtering, and more. It explains the basic MVC structure with models representing data, views representing presented information, and controllers serving as intermediaries. The document demonstrates how CodeIgniter handles URLs in a segment-based approach and describes the roles of controllers, views, models, helpers, libraries, and hooks within a CodeIgniter application. Code examples are provided to illustrate how each component works.
Atlanta JUG - Integrating Spring Batch and Spring IntegrationGunnar Hillert
This document provides an overview and introduction to Spring Batch, Spring Integration, and Spring XD. It discusses key concepts and features of Spring Batch for batch processing and Spring Integration for enterprise integration. It also demonstrates how Spring Batch and Spring Integration can be used together for batch integration use cases. Finally, it introduces Spring XD for unified data ingestion, analytics, and export capabilities using existing Spring projects. The presentation includes code samples and links to documentation and GitHub repositories for further information.
Ruby on Rails is an open-source web application framework that uses the Model-View-Controller pattern. It uses Ruby as its programming language. Rails provides conventions for building database-backed web applications, including generating scaffolding for basic CRUD operations. The document demonstrates how to generate a Rails application, scaffold a Bookmarks model, add validations and associations to Categories, and integrate Ajax functionality. Rails emphasizes conventions over configuration for directory structure and default actions.
Ruby on Rails is an open-source web application framework that uses the Model-View-Controller pattern. It uses Ruby as its programming language. Rails provides conventions for building database-backed web applications, including scaffolding that automatically generates the basic structure and files needed for a model. Rails emphasizes conventions over configuration, including naming conventions and default directory structures. The document provides an overview of Rails and demonstrates how to generate a sample bookmarks application using Rails, including generating models, views, controllers, and associations between models.
This document provides a fast-paced introduction to Ruby, Rails, and additional technologies. It begins with an overview of Ruby basics, syntax, and uses beyond scripts. It then covers Rails fundamentals including MVC architecture, scaffolding, models, views, controllers, and routes. Additional topics discussed include gems, Git, and deploying to Heroku. The document concludes by outlining a sample project to build a marketplace for buying and selling robot spare parts.
This document summarizes the Rails request lifecycle and describes various middlewares used in Rails. It begins by explaining what a request is and how it travels from the browser to the Rails application. It then discusses the roles of the web server and app server. The bulk of the document describes each middleware in the Rails stack, from Rack middlewares to ActionDispatch middlewares to ActiveRecord middlewares. It explains what each middleware does to filter requests and responses. Finally, it outlines how the request travels through the middleware stack to the routes, controller, and back out again to complete the response sent to the client.
Ruby on Rails is a full-stack web application framework written in Ruby. It allows developers to build database-backed web applications rapidly using conventions like MVC pattern and follows "convention over configuration" principle. Rails includes features like Active Record (ORM), validations, migrations, scaffolding, routing and helpers to help develop web applications quickly. Testing is an important part of Rails development using tools like RSpec, Factory Girl, Cucumber and Capybara.
Ruby on Rails is a full-stack web application framework written in Ruby. It uses the MVC pattern and convention over configuration principles. Rails makes it possible to develop database-backed web applications rapidly by minimizing configuration through conventions and providing scaffolding. Key Rails concepts include Active Record for ORM, migrations for schema changes, routing for URLs, controllers for application logic, views for presentation, and testing frameworks. Rails emphasizes productivity through conventions that reduce configuration overhead.
Ember.js - introduction
I have searched for Ember ppt in the internet. Got many things but not like structured... So i have just combined and made a new one..
I am just learning and not an expert. Please share your comments, so i can keep up myself..
Ruby on Rails, often simply referred to as Rails, is an open-source web application framework written in Ruby. It follows the Model-View-Controller (MVC) architectural pattern, which separates an application into three interconnected components to promote code Ruby Rails Web Development organization and maintainability. Ruby on Rails has gained popularity for its focus on developer productivity and its convention-over-configuration philosophy, which significantly reduces the need for boilerplate code and configuration.
This document provides an overview of a Rails bootcamp covering various topics related to Ruby on Rails development. It discusses what Ruby and Rails are, common Rails patterns and principles like MVC and DRY, version control with Git, and deploying projects to GitHub. It then outlines several iterations of developing a basic blog application, starting with generating models and controllers, adding features like comments, tags, authentication, and more. Each iteration utilizes a Git workflow and builds upon the previous work to incrementally develop the application.
The document discusses Rails interview questions and answers. It covers common questions about what Rails is and its components like Action Pack, Action Mailer, Active Model, Active Record, Active Resource, and Active Support. Other questions addressed include RESTful architecture, advantages of Rails, scaffolding, render vs redirect_to, ORM, model associations, helpers, filters, MVC pattern, sessions vs cookies, and more.
This document provides an introduction and overview of Ruby on Rails. It discusses that Rails is a full-stack web application framework written in Ruby that follows conventions like DRY and MVC. It allows developers to build database-backed web applications more quickly compared to other frameworks. The document then covers key Rails concepts like migrations, Active Record, associations, validations, and the query interface. It provides examples of generating models and controllers and implementing RESTful actions to perform CRUD operations.
The document provides information about a PHP framework lecture on Laravel. It includes the course code, department, lecturer, semester, and lecture outline. The lecture covers an introduction to Laravel, installing and running the framework, the directory structure, routing basics, the view engine Blade, and creating views. Key points about Laravel are that it makes tasks like authentication and caching easy and offers a powerful tool called Artisan to perform repetitive tasks. Composer is used to manage Laravel dependencies.
Here are the changes to make:
1. In app/views/people/index.html.erb, change "Listing people" to "My Class List"
2. Update the each loop to display first initial and last name:
<% @people.each do |person| %>
<td><%= person.first_name[0] %>. <%= person.last_name %></td>
<% end %>
This document provides an overview of Ruby on Rails, including:
[1] It describes Ruby on Rails as a web application framework written in Ruby that uses the model-view-controller pattern and includes features like REST, databases support, and code generation.
[2] The architecture of Rails is explained, including its modules like Action Pack, Active Record, and Railties.
[3] An example application is created to demonstrate generating a project, controller, and view in Rails.
This document provides an overview of learning to code for a startup minimum viable product (MVP) using Ruby on Rails. It discusses setting up a development environment, using Git version control, the Ruby programming language basics, Rails models and object-relational mapping, authentication with Devise, Rails controllers and routing, and using scaffolding to build out a sample Mini Twitter app with Posts and Users models. The goal is to provide attendees with the necessary skills to build a basic MVP for a startup.
Code for Startup MVP (Ruby on Rails) Session 1Henry S
First Session on Learning to Code for Startup MVP's using Ruby on Rails.
This session covers the web architecture, Git/GitHub and makes a real rails app that is deployed to Heroku at the end.
Thanks,
Henry
I prepared this presentation to introduce Ruby on Rails to
a group of students at Università di Catania.
It is not enough to get a good grasp of Rails, the
presentation in fact was supported by live coding, where
I started created a Phrasalbook (no more blog engine
please :) )
This document discusses Ruby gems, including:
- How to interact with gems using the gem command to search, install, uninstall, list, and view documentation for gems.
- The standard structure for gems including code, tests, documentation, and a gemspec file.
- How to create your own gem including naming conventions, building a gemspec, and publishing the gem to RubyGems.org.
Deepak H B provides contact information and an overview of networking in Ruby. Ruby uses sockets for networking rather than core classes. Sockets allow reading and writing data to other computers like files. Simple client and server examples are provided using TCPSocket and TCPServer classes. Datagrams can also be used with UDPSocket for lower overhead communication. Multiplexing servers are discussed that allow serving multiple clients simultaneously using Kernel.select. Finally, prebuilt libraries are mentioned for implementing protocols like HTTP, FTP, SMTP, POP and IMAP.
The document discusses Ruby's input and output capabilities. It covers:
- Ruby provides two interfaces for I/O - simple print/gets methods and more advanced methods in the Kernel module.
- All I/O is handled by the IO base class, which File and BasicSocket subclass. IO objects represent bidirectional channels between Ruby and external resources.
- Files can be opened for reading, writing or both using File.new/File.open, specifying a mode. File streams support various methods for reading and writing lines and bytes.
- Random access methods like pos, tell, seek allow reading/writing specific locations in files and strings.
This document provides an introduction to exception handling in Ruby. It defines what exceptions are and how they are raised when errors occur. It describes how to handle exceptions using rescue clauses and how to define custom exception classes. It also covers different ways to raise exceptions and additional exception handling concepts like ensure clauses.
This document provides information about methods and functional programming in Ruby. It defines what a method is, how methods are defined and invoked, and how they can return values. It discusses defining simple methods, method return values, singleton methods, and undefining methods. It also covers method name conventions, omitting parentheses in method calls, variable-length argument lists, default parameter values, and using hashes for named arguments. The document concludes by explaining procs and lambdas, how they are created, and how they are invoked differently than regular methods.
- Ruby is an object-oriented language where everything is an object and classes define methods that objects respond to.
- Classes can inherit and override methods from superclasses and include methods from modules.
- The initialize method is used as a constructor to initialize instance variables. Accessors provide access to instance variables.
- Common methods like +, -, *, [] can be defined for a class to allow arithmetic and array-like access to objects.
This document provides an overview of control structures and flow altering statements in Ruby. It discusses conditionals like if/else, unless, case; loops like while, until, for/in; iterators and enumerable objects; and flow altering statements like return, break, next, redo. Conditionals and loops allow altering the sequential execution of code. Iterators and enumerables provide concise ways to iterate over objects. Statements like return and break change the normal flow of control.
The document summarizes key concepts in Ruby including expressions, operators, literals, variables, constants, method invocations, assignments, and parallel assignments. Expressions can be combined with operators and evaluated to produce values. Variables, constants, literals, and keywords also evaluate to values that can be used in expressions. Methods are invoked by sending messages to objects and can accept arguments. Assignments are used to set values to variables, attributes, and array elements. Parallel assignments allow setting multiple variables at once.
This document provides information about various data types in Ruby including numbers, text, arrays, hashes, and more. It discusses how numbers can be integers, floats, complexes, big decimals, and rationals. It also covers string literals and interpolation, character literals, and various string operators and methods. Arrays and hashes are introduced as mutable collections that can hold heterogeneous data and are accessed via indexes.
Deepak H B is a web application developer who specializes in Ruby on Rails. He provides his contact information including email and LinkedIn profile. The document then discusses installing Ruby through different methods like RVM, basics of using RVM to manage Ruby versions and gems, and how to run Ruby code interactively through IRB or by creating Ruby program files. It also briefly mentions Ruby documentation tools like RDoc and RI.
Introduction to AI for Nonprofits with Tapp NetworkTechSoup
Dive into the world of AI! Experts Jon Hill and Tareq Monaur will guide you through AI's role in enhancing nonprofit websites and basic marketing strategies, making it easy to understand and apply.
हिंदी वर्णमाला पीपीटी, hindi alphabet PPT presentation, hindi varnamala PPT, Hindi Varnamala pdf, हिंदी स्वर, हिंदी व्यंजन, sikhiye hindi varnmala, dr. mulla adam ali, hindi language and literature, hindi alphabet with drawing, hindi alphabet pdf, hindi varnamala for childrens, hindi language, hindi varnamala practice for kids, https://www.drmullaadamali.com
How to Fix the Import Error in the Odoo 17Celine George
An import error occurs when a program fails to import a module or library, disrupting its execution. In languages like Python, this issue arises when the specified module cannot be found or accessed, hindering the program's functionality. Resolving import errors is crucial for maintaining smooth software operation and uninterrupted development processes.
This presentation includes basic of PCOS their pathology and treatment and also Ayurveda correlation of PCOS and Ayurvedic line of treatment mentioned in classics.
How to Build a Module in Odoo 17 Using the Scaffold MethodCeline George
Odoo provides an option for creating a module by using a single line command. By using this command the user can make a whole structure of a module. It is very easy for a beginner to make a module. There is no need to make each file manually. This slide will show how to create a module using the scaffold method.
Strategies for Effective Upskilling is a presentation by Chinwendu Peace in a Your Skill Boost Masterclass organisation by the Excellence Foundation for South Sudan on 08th and 09th June 2024 from 1 PM to 3 PM on each day.
A workshop hosted by the South African Journal of Science aimed at postgraduate students and early career researchers with little or no experience in writing and publishing journal articles.
How to Add Chatter in the odoo 17 ERP ModuleCeline George
In Odoo, the chatter is like a chat tool that helps you work together on records. You can leave notes and track things, making it easier to talk with your team and partners. Inside chatter, all communication history, activity, and changes will be displayed.
বাংলাদেশের অর্থনৈতিক সমীক্ষা ২০২৪ [Bangladesh Economic Review 2024 Bangla.pdf] কম্পিউটার , ট্যাব ও স্মার্ট ফোন ভার্সন সহ সম্পূর্ণ বাংলা ই-বুক বা pdf বই " সুচিপত্র ...বুকমার্ক মেনু 🔖 ও হাইপার লিংক মেনু 📝👆 যুক্ত ..
আমাদের সবার জন্য খুব খুব গুরুত্বপূর্ণ একটি বই ..বিসিএস, ব্যাংক, ইউনিভার্সিটি ভর্তি ও যে কোন প্রতিযোগিতা মূলক পরীক্ষার জন্য এর খুব ইম্পরট্যান্ট একটি বিষয় ...তাছাড়া বাংলাদেশের সাম্প্রতিক যে কোন ডাটা বা তথ্য এই বইতে পাবেন ...
তাই একজন নাগরিক হিসাবে এই তথ্য গুলো আপনার জানা প্রয়োজন ...।
বিসিএস ও ব্যাংক এর লিখিত পরীক্ষা ...+এছাড়া মাধ্যমিক ও উচ্চমাধ্যমিকের স্টুডেন্টদের জন্য অনেক কাজে আসবে ...
Macroeconomics- Movie Location
This will be used as part of your Personal Professional Portfolio once graded.
Objective:
Prepare a presentation or a paper using research, basic comparative analysis, data organization and application of economic information. You will make an informed assessment of an economic climate outside of the United States to accomplish an entertainment industry objective.
3. Introduction
• Rails are a web application development framework written in Ruby.
• It is designed to make programming web applications easier by making
assumptions about what every developer needs to get started.
• If you learn “The Rails Way” you’ll probably discover a tremendous
increase in productivity.
• The Rails philosophy includes several guiding principles:
– DRY- “Don’t Repeat Yourself” suggests that writing the same code over and
over again is a bad thing.
– Convention over Configuration- means that Rails makes assumptions about
what you want to do and how you’re going to do it.
– REST is the best pattern for web application- organizing your application
around resources and standard HTTP verbs is the fastest way to go.
4. The MVC Architecture
At the core of Rails is the Model, View, Controller architecture, usually
just called MVC. MVC benefits include:
– Isolation of business logic from the user interface
– Ease of keeping code DRY
– Making it clear where different types of code belong for easier
maintenance
Models
A model represents the information (data) of the application and the
rules to manipulate that data. In the case of Rails, models are primarily
used for managing the rules of interaction with a corresponding
database table
5. Contd..
Views
• Views represent the user interface of your application.
• In Rails, views are often HTML files with embedded Ruby code that
perform tasks related solely to the presentation of the data.
Controllers
• Controllers provide the ‘glue’ between models and views.
• In Rails, controllers are responsible for processing the incoming
requests from the web browser, interrogating the models for data,
and passing that data on to the views for presentation.
6. Components of Rails
• Rails ship as many individual components.
• Action Pack
– Action Controller
– Action Dispatch
– Action View
• Action Mailer
• Active Model
• Active Record
• Active Resource
• Active Support
• Railties
7. REST
• Rest stands for Representational State Transfer and is the
foundation of the RESTful architecture.
• REST in terms of Rails boils down to two main principles
– Using resource identifiers such as URL’s to represent
resource.
– Transferring representations of the state of that resource
between system components.
• For example, DELETE /photos/17
8. Creating New Rails Application
Installing Rails
• gem install rails
• rails –v
Creating the Blog Application
• rails new blog
• cd blog
9. File/Folder Purpose
app/
Contains the controllers, models, views and assets for your
application. You’ll focus on this folder for the remainder of this
guide.
config/
Configure your application’s runtime rules, routes, database,
and more. This is covered in more detail in Configuring Rails
Applications
config.ru Rack configuration for Rack based servers used to start the
application.
db/ Contains your current database schema, as well as the
database migrations.
doc/ In-depth documentation for your application.
Gemfile
Gemfile.lock
These files allow you to specify what gem dependencies are
needed for your Rails application.
lib/ Extended modules for your application.
10. Contd..
File/Folder Purpose
log/ Application log files.
public/ The only folder seen to the world as-is. Contains the static files and
compiled assets.
Rakefile
This file locates and loads tasks that can be run from the command
line. The task definitions are defined throughout the components of
Rails. Rather than changing Rakefile, you should add your own tasks
by adding files to the lib/tasks directory of your application.
README.rdoc
This is a brief instruction manual for your application. You should
edit this file to tell others what your application does, how to set it
up, and so on.
script/ Contains the rails script that starts your app and can contain other
scripts you use to deploy or run your application.
test/ Unit tests, fixtures, and other test apparatus. These are covered
in Testing Rails Applications
tmp/ Temporary files
vendor/
A place for all third-party code. In a typical Rails application, this
includes Ruby Gems, the Rails source code (if you optionally install
it into your project) and plugins containing additional prepackaged
functionality.
11. Migrations
• A migration is subclass of ActiveRecord::Migration that implements two methods:
up and down.
• Active Record provides methods that perform common data definition tasks in a
database independent way.
– add_column
– add_index
– change_column
– change_table
– create_table
– drop_table
– remove_column
– remove_index
– rename_column
• If you need to perform tasks specific to your database then the execute method
allows you to execute arbitrary SQL.
• Migrations are stored as files in the db/migrate directory, one for each migration
class.
12. Contd..
• The name of the file is of form YYYYMMDDHHMMSS_create_products.rb.
• You can revert to old number scheme (2.1+) by adding following line of code in
application.rb
config.active_record.timestamped_migrations = false
• Supported types are as follows
• :binary
• :Boolean
• :date
• :datetime
• :decimal
• :float
• :integer
• :primary_key
• :string
• :text
• :time
• :timestamp
13. Creating a Migrations
• Rails generate model Product name:string description:text
• Will create a migration file
class CreateProducts < ActiveRecord::Migration
def change
create table :products do |t|
t.string :name
t.text :description
t.timestamp
end
end
end
14. Contd..
• Creating stand alone migration
rails generate migration AddPartNumberToProducts
part_number:string
• Will create a migration file
class AddPartNumberToProducts < ActiveRecord::Migration
def change
add_column :products, :part_number, :string
end
end
15. Change Tables
• A close cousin of create_table is change_table used for changing
existing tables.
• It is used in a similar fashion to create_table but the object yielded
to the block knows more tickes.
change_table :products do |t|
t.remove :description, :name
t.string :part_name
t.index :part_number
t.rename :upccode, :upc_code
16. Special Helpers
• t.timestamps, This will add both created_at and updated_at
columns to table.
• t.references, will create appropriate foreign key column
accordingly.
t.references category => category_id
• Similarly, t.references attachment, :polymorphic => {:default
=> ‘photo’}. Will add an attachment_id column and a string
attachment_type column with a default value of “Photo”.
17. Running Migrations
• Rails provides a set of rake tasks to work with migrations which boil
down to running certain sets of migrations.
• The very first migration related task,
rake db:migrate /VERSION=version_number
• In its most basic form it just runs the up or change method for all
the migration that not yet been run or only version number
migration file if specified.
• To rollback the changes
rake db:rollback
rake db:rollback STEP=3, will run down method from last 3
migrations.
18. Schema Files
• Migrations are not the authoritative source for your database
schema.
• This role fails to either db/schema.rb or and SQL file which
Active Record generates by examining the database.
• They are not designed to be edited, they just represent the
current state of the database.
• Schema files are also useful if you want a quick look at what
attributes an Active Record object has.
19. Active Record Validations and Callbacks
• During the normal operation of a Rails application, objects may be
created, updated, and destroyed. Active Record provides hooks into
this object life cycle so that you can control your application and its data.
• Validations allow you to ensure that only valid data is stored in your
database. Callbacks and observers allow you to trigger logic before or after
an alteration of an object’s state.
Validations
• Validations are used to ensure that only valid data is saved into your
database.
• There are several ways to validate data before it is saved into your
database:
– Database constraints or stored procedures.
– Client-side validation
– Controller level validation
– Model-level validation
20. When does validation happen
• There are two kinds for active record objects
– Those that correspond to a row inside your database
– Those that do not. When you create a fresh object
• new, save, new_record?
• The following methods trigger validations and will save the object
to the database only if the object is valid:
– create
– create!
– save
– save!
– update
– update_attributes
– update_attributes!
• The save also has the ability to skip validations if passed :validate =>
false as argument.
21. Contd..
• The following methods skips the validations and will save the object
to the database regardless of its validity.
– decrement!
– decrement_counter
– increment!
– increment_counter
– toggle!
– touch
– update_all
– update_attribute
– update_column
– update_counters
• valid? and invalid? To check the validity of an object.
• errors method is used only after validation have been run.
22. Validation Helpers
• Active record offers many pre-defined validation helpers that can
use directly inside your class definitions.
• These helpers provide common validation rules. Every time a
validation fails, an error message is added to the
object’s errors collection, and this message is associated with the
attribute being validated.
• Each helper accepts arbitrary number of attributes.
23. Contd..
• The helper methods are as follows
a. acceptance
validates :terms_of_services, :acceptance => true
b. validates_associated
has_many :books
validates_associated :books
c. confirmation
validates :email, :confirmation => true
d. exclusion
validates :subdomain, :exclusion => {:in => %w{www us ca jp),
:message => “Sumdomain %{value} is reserved.”}
e. format
validates :legacy_code, :format => {:with => /A[a-zA-Z]+z/,
:message => “Only letters are allowed”}
24. Contd..
f. Inclusion
g. length
validates :name, :length => {:in => 2..20}
h. numericality
validates :points, :numericality => true
i. presence
validates :name, :presence => true
j. uniqueness
validates :email, :uniqueness => true
k. validates_each
validates_each :name, :surname do |record, attr, value|
record.errors.add(attr, 'must start with upper case') if value =~ /A[a-z]/
end
25. Contd..
l. validates_with
class Person < ActiveRecord::Base
validates_with GoodnessValidator, :fields => [:first_name,
:last_name]
end
class GoodnessValidator < ActiveModel::Validator
def validate(record)
if options[:fields].any?{|field| record.send(field) == "Evil" }
record.errors[:base] << "This person is evil"
end
end
end
26. Contd..
• There are common validation options:
a. :allow_nil
validates :size, :inclusion => {:in => %w{small medium large}),
:message => “%{value} is not valid”, :allow_nil => true
b. :allow_blank
validates :title, :length => {:is=>5}, :allow_blank => true
c. :message
d. :on
validates :email, :uniqueness => true, :on => create
27. Errors
• Returns an instance of the class ActiveModel::Errors containing all errors.
• Each key is the attribute name and the value is an array of strings with all errors.
• errors[] is used when you want to check the error messages for a specific attribute.
• It returns an array of strings with all error messages for the given attribute, each
string with one error message.
• errors.add method lets you manually add messages that are related to particular
attributes.
• Errors[:base] add error messages that are related to the object’s state as a whole,
instead of being related to a specific attribute.
• errors.clear method is used when you intentionally want to clear all the messages
in the errors collection.
• errors.size method returns the total number of error messages for the object.
28. Callbacks
• Callbacks are methods that get called at certain moments of an object’s
life cycle.
• With callbacks it is possible to write code that will run whenever an Active
Record object is created, saved, updated, deleted, validated, or loaded
from the database.
29. Contd..
Callback Registration
• In order to use available callbacks, you need to register them.
before_validation :ensure_login_has_a_value
protected
def ensure_login_has_a_value
if login.nil?
self.login = email unless email.blank?
end
End
• You can implement the callbacks as ordinary methods and use a macro-
style class method to register them as callback.
before_create do |user|
user.name = user.login.capitalize if user.name.blank?
end
30. Observers
• Observers are similar to callbacks, but with important differences.
• Whereas callbacks can pollute a model with code that isn’t directly related to its
purpose, observers allow you to add the same functionality without changing the
code of the model.
Creating Observers
• rails generate observer User
• generates app/models/user_observer.rb containing the observer class
UserObserver
• The observer method receive the observer model as a parameter.
class UserObserver < ActiveRecord::Observer
def after_create(model)
# code
end
End
• Observers are conventionally placed inside of your app/models directory and
registered in your application’s config/application.rb file.
config.active_record.observers = :user_observer
31. Active Record Associations
The Types of Association
Rails supports 6 types of associations
1. belongs_to
2. has_one
3. has_many
4. has_many :through
5. has_one :through
6. has_and_belongs_to_many
32. Contd..
belongs_to Associstion
• A belongs_to association sets up a one to one connection with
another model, such that each instance of the declaring model
“belong to” one instance of the other model.
33. Contd..
has_one Association
• This association indicates that each instance of a model contains or
possesses on instance of another model.
38. Layouts and Rendering
Creating Responses
• From controller point of view, there are three ways to create an
HTTP responses:
• Call render to create a full response to send back to the browser.
• Call redirect_to to send an HTTP redirect status code to the
browser.
• Call head to create a response consisting solely of HTTP headers to
send back to the browser.
39. Contd..
• Rendering by Default: Convention over Configuration
• Using render
• Render Nothing
render :nothing => true
• Render an Action view
If you want to render the view that corresponds to a different
action within the same template.
• Rendering actions Template from another controller
render ‘products/show’ or render :template =>
‘products/show’
• Rendering an Arbitrary file
render :file => ‘apps/warehouse/app/views/products/show’
By default, the file is rendered without using the current
layout. If you want rails to put the file into the current layout, you need
to add the :layout =>true option.
40. Contd..
• Using render with inline
render :inline => “<% products.each do |p|
%><p><%=p.name%></p><%end%>”
• Rendering Text
render :text => “OK”
By default, the file is rendered without using the current layout. If
you want rails to put the file into the current layout, you need to add the
:layout => true option.
• Rendering JSON
render :json => @product
• Rendering XML
render :xml => @product
• Rendering Javascript
render :js => “alert(‘Hello world!’);”
41. Finding Layouts
• To find the current layout, Rails will first looks for a file in
app/views/layouts with the same base name as the controller.
• If there is no such controller-specific layout, Rails will use
app/views/layouts/application.html.erb or
app/views/layouts/application.builder. If there is no .erb layout,
Rails will use a .builder layout if one exists.
• Rails also provides several ways to more precisely assign specific
layouts to individual controllers and actions.
class CustomController < ActionController::Base
layout “custom”
end
42. Using redirect_to
redirect_to photos_url/:back
Asset Tag Helpers
• Asset tab helpers provide methods for generating HTML that link
views to feeds, javascript, stylesheets, images, videos and audios.
• There are six asset tag helpers available in Rails:
– auto_discovery_link_tag
– javascript_include_tag
– stylesheet_include_tag
– image_tag
– video_tag
– audio_tag
43. Action Controller
Methods and Actions
• A controller in a Ruby class which inherits from
ApplicationController and has methods just like any other class.
• When your application receives a request, the routing will
determines which controller and action to run, then Rails creates an
instance of that controller and runs the method with the same
name as the action.
class ClientsController < ApplicationController
def new
end
end
44. Parameters
• You will probably want to access the data sent by the user or other
parameters in your controller actions.
• There are two types of parameters
– Query string parameters
– POST data
• These parameters are accessible from params.
• Hash and Array Pararmeters
• JSON/XML Parameters
• Routing parameters
• ##002#
45. Session
• Application has a session for each user in which you can store small
amounts of data that will be persisted between requests.
• The session is only available in the controller and the view and the view
and can use one of the different storage mechanisms:
– ActionDispatch::Session::CookieStore – Stores everything on the client
– ActiveRecord::SessionStore – Stores in database using ActiveRecord.
– ActionDispatch::Session::CacheStore – Stores the data in the Rails cache.
– ActionDispatch::Session::MemCacheStore – Stores the data in a memcached
cluster.
• All session stores use a cookie to store a unique ID for each session.
• This ID is used to lookup the session data on the server.
• The CookieStore can store around 4kB of data much less then the others
but this is usually enough.
• If you need a different session storage mechanism, you can change it in
the
config/intializers/session_store.rb file
YourApp::Application.config.session_store :active_record_store
46. Accessing the session
• In controller the sessions can be accessed through the
session instance method.
• Session values are stored using key/value pairs like a hash
class ApplicationController < ActionController::Base
private
def current_user
@current_user ||= session[:current_user_id] &&
User.find(session[:current_user_id])
end
end
47. The flash
• The flash is a special part of the session which is cleared with each
request.
• This means that values stored there will only be available in the
next request, which is useful for storing error messages etc.
• It is accessed in much the same way as the session.
def destroy
session[:current_user_id] = nil
flash[:notice] = “You have been logged out successfully”
redirect_to root_url
End
• By default, adding values to flash makes them available to the next
request, but sometimes you may want to access those values in the
same request.
48. • Filters
• Filters are methods that are run before, after or around a controller action.
• Filters are inherited, so if you set a filter on ApplicationController, it will be run on
every controller in your application.
• A common before filter is one which requires that a user is logged in for an action
to be run.
class ApplictionController < ActionController::Base
before_filter :require_login
private
def require_login
unless require_login?
flass[:error] = “You must be logged to access this section”
redirect_to new_login_url
end
end
def logged_in?
!!current_user
end
end
49. Contd..
• In addition to before_filters, you can also run filters after an
action has been executed, or both before and after.
after_filter :method_name
around_filter :method_name
50. Routing
• The rails router recognizes URLs and dispatches them to a
controllers action.
• It can also generate paths and URL’s, avoiding the need to
hardcode strings in your views.
• When Rails application receives an incoming request
GET /patients/17
• It asks the router to match it to a controller action. If the first
matching route is
match “/patients/:id => “patients#show”
51. Resource Routing
• Resource routing allows you to quickly declare all of the common
routes for a given resourceful controller.
• Instead of declaring separate routes for your index, show, new, edit,
create, update and destroy actions.
• A resourceful declares them in a single line of code.
Resources :photos
• In Rails, a resourceful route provides a mapping between HTTP
verbs and URLs to controller actions.
• By convention, each action also maps to particular CRUD operations
in a database.
52. Contd..
HTTP Verb Path action used for
GET /photos index display a list of all photos
GET /photos/new new return an HTML form for
creating a new photo
POST /photos create create a new photo
GET /photos/:id show display a specific photo
GET /photos/:id/edit edit return an HTML form for
editing a photo
PUT /photos/:id update update a specific photo
DELETE /photos/:id destroy delete a specific photo
53. Contd..
• Creating a resourceful route will also expose number of helpers to the controller in
your application. In the case of resources :photos
– The photos_path => /photos
– The new_photo_path => /photos/new
– The edit_photo_path(:id) => /photos/:id/edit
– The photo_path(:id) => /photos/:id
• The groups of controller can organized in under a namespace. Most commonly, the
number of administrative controllers are grouped under an Admin::namespace.
– This will create a number of routes for each of the posts and comments
controller for
Admin::PostsController.
namespace :admin do
resource :posts, :comments
end
– To route /posts to Admin::PostsControllers
resources :posts, :module => “admin”
– To route /admin/posts to PostsConroller
resources :posts, :path => “admin/posts”
54. Contd..
• Multiple resources can be defined in either of the two ways
– resources :photos, :books, :videos
– resources :photos
resources :books
resources :videos
• Its common to have resources that are logically children of other resources (Nested routes)
resources :magazines do
resources :ads
end
• This is not limited to seven routes that RESTful routing creates by default. You may add
additional routes that apply to the collection or individual members of the collections.
– To add member routes
resources :photos do
member do
get “preview”
end
End
– To add collection routes
reourcees :photos do
collection do
get “search”
end
end
55. Non Resourceful Routes
• Rails has powerful support for routing arbitrary URL’s to actions.
• Here, the groups of routes are not automatically generated. Instead, you setup
each route within your application separately.
Bound Parameters
match ‘:controller(/:action(/:id))’
The series of symbols that Rails maps to parts of an incoming HTTP requests
Dynamic Segments
match ‘:controller/:action/:id/:user_id
You can set up as many dynamic segments with a regular route as you like.
The Qurey String
Defining Defaults
match ‘photos/:id’ => ‘photos#show’
Naming Routes
match ‘exit’ => ‘sessions#destroy’, :as => :logout,
This creates logout_path and logout_url as named helpers in your application.
56. HTTP Verb Constraints
• You can use the :via option to constraint the request to one or more HTTP
methods
match ‘photos/show’ => ‘photos#show’, :via => :get
• You can also permit more than one verb to a single route
match ‘photos/show’ => ‘photos#show’, :via => [:get, :post]
Segment Constraints
• The :constraints option enforce a format for a dynamic segment
match ‘/photos/:id’ => ‘photos#show’, :constraints => {:id => /[A-Z]d{5}/
• The above route would match paths such as /photos/A12345.
Route Globbing
• Route globbing is a way to specify that a particular parameter should be matched
to all the remaining parts of a route.
match ‘photos/*other’ => ‘photos#unknown’
• This route would match /photos/12 or /photos/long/path/to/12. Setting
params[:other] to “12” or “long/path/to/12”.
57. ERB Templating
• The ERB is the feature of Ruby that enables you to conveniently generate any kind
of text, in any quantity, from templates.
• The templates themselves combine plain text with Ruby code for variable
substitution and flow control, which makes them easy to write and maintain.
• Although ERB is commonly seen generating web pages, it is also used to produce
xml documents, RSS feeds, source code and other forms of structured text file.
• The main component of ERB is a library which you can call within your Ruby
applications and rake tasks.
• This library accepts any string as a template, and imposes no limitations on the
source of the template.
• The definition of a template can be entirely within your code or store it in an
external location and load it as required.
• Ruby distributions also includes command line utility that enables you to process
templates that are held in files without writing ay additional code. This utility is
called erb.
58. Writing Templates
• ERB copies the text portions of the template directly to the
generated document, and only processes code that is identified by
markers.
• Most ERB templates only use a combination of two tag markers,
each of which cause the enclosed code to be handled in a particular
way.
• A tag with an equals sign indicates that enclosed code is
an expression, and that the renderer should substitute the code
element with the result of the code (as a string) when it renders the
template.
Hello, <%= @name %>
Today is <%= Time.now.strftime(“%A”) %>
59. Contd..
• Tags without the equals sign denote that the enclosed code is a scriptlet
<ul>
<% for @item in @shopping_list %>
<li><%= @item%></li>
<% end %>
</ul>
• By default , a newline character is added to the page after the position of
each tag. To suppress this newline. To suppress the newline add hyphen
to the trailing tags in Rails template.
• A file that contains an ERB template may have any name, but it is the
convention that the name of file should end with the .erb extension.
• Rails requires template files to have the extension of the output type,
followed by .erb, so that a name like layout.html.erb indicates a
HTML template.
60. Using erb library
• This is very simple example
require ‘erb
@weekday = Time.now.strftime(“%A”)
simple_template = “Today is <%=@weekday %>.”
Renderer = ERB.new(simple_template)
puts output = renderer.result()
• ERB only processes the template when result is called.
• This means that the output will show the values of variables as they are at
the moment when the result is rendered, not when the ERB object was
defined.
61. Running erb in a Sandbox
• You may protect your application from ERB by running it in a new
thread.
renderer = ERB.new(template, 3)
• The third parameter of new specifies optional modifiers, most of
which alter when newline characters will be automatically added to
the output. For example, ERB will not print newlines after tags if
you give > as the third parameter.
renderer = ERB.new(template, 3, ‘>’)
62. Running erb on commandline
• The erb utility processes a given template and sends the result to
the standard output.
erb my-template.txt.erb > new-file.txt
• The template can automatically use built-in Ruby classes, such
as String and File.
• To allow it to access standard or third-party libraries, use the -
r option. This option works in the same way as the require keyword.
• The below example processes a template that uses Abbrev and
IPAddr libraries
erb –r abbrev –r ipaddr my-template.txt.erb > new-file.txt
• Use the –S option to specify a safe level that isolates the template
processing.
erb –S 3 my-template.txt.erb > new-file.txt