Rails, Angular, Postgres, and Bootstrap Powerful, Effective, and Efficient Full-Stack Web Development (David Bryant Copeland) (Z-Library)

Author: David Bryant Copeland

非小说

As a Rails developer, you care about user experience and performance, but you also want simple and maintainable code. Achieve all that by embracing the full stack of web development, from styling with Bootstrap, building an interactive user interface with AngularJS, to storing data quickly and reliably in PostgreSQL. Take a holistic view of full-stack development to create usable, high-performing applications, and learn to use these technologies effectively in a Ruby on Rails environment.

📄 File Format: PDF
💾 File Size: 8.7 MB
73
Views
0
Downloads
0.00
Total Donations

📄 Text Preview (First 20 pages)

ℹ️

Registered users can read the full content for free

Register as a Gaohf Library member to read the complete e-book online for free and enjoy a better reading experience.

📄 Page 1
www.it-ebooks.info
📄 Page 2
www.it-ebooks.info
📄 Page 3
Early praise for Rails, Angular, Postgres, and Bootstrap This book is a fantastic resource for anyone looking to gain a practical understand- ing of full-stack development using contemporary, ubiquitous technologies. I was particularly impressed by how well the author was able to cover so many different software components in such a constructive and cohesive manner. As an engineer who spends most of my time at the data layer, I walked away with a ton of helpful insight into the other layers of the typical application stack. ➤ Matthew Oldham Director of data architecture, Graphium Health A book that deals with integrating Angular into Rails is something I’ve been waiting a long time for, and what’s here is a definite step above existing online tutorials. Like the author, I’m used to viewing different database management systems as black boxes that are much like each other, and this book made me reconsider that line of thinking. I highly recommend this book for Rails developers who want to try Angular and make use of PostgreSQL’s advanced features. ➤ Nigel Lowry Company director, Lemmata Rails, Angular, Postgres, and Bootstrap is a powerful resource for all software en- gineers interested in full-stack development. No matter your proficiency at each level in the stack, you’ll acquire a new technique that’s immediately applicable to your project. ➤ Simeon Willbanks Lead software engineer, Stitch Fix www.it-ebooks.info
📄 Page 4
This book provides beginner developers with solid steps to get “your” application running and to be able to see/do it yourself. I recommend the book to Rails devel- opers beginning their learning journey with Angular. ➤ Maricris Nonato Senior Ruby on Rails developer, Premiere Speakers Bureau www.it-ebooks.info
📄 Page 5
Rails, Angular, Postgres, and Bootstrap Powerful, Effective, and Efficient Full-Stack Web Development David Bryant Copeland The Pragmatic Bookshelf Dallas, Texas • Raleigh, North Carolina www.it-ebooks.info
📄 Page 6
Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and The Pragmatic Programmers, LLC was aware of a trademark claim, the designations have been printed in initial capital letters or in all capitals. The Pragmatic Starter Kit, The Pragmatic Programmer, Pragmatic Programming, Pragmatic Bookshelf, PragProg and the linking g device are trade- marks of The Pragmatic Programmers, LLC. Every precaution was taken in the preparation of this book. However, the publisher assumes no responsibility for errors or omissions, or for damages that may result from the use of information (including program listings) contained herein. Our Pragmatic courses, workshops, and other products can help you and your team create better software and have more fun. For more information, as well as the latest Pragmatic titles, please visit us at https://pragprog.com. The team that produced this book includes: Fahmida Y. Rashid (editor) Potomac Indexing, LLC (index) Liz Welch (copyedit) Dave Thomas (layout) Janet Furlow (producer) Ellie Callahan (support) For international rights, please contact rights@pragprog.com. Copyright © 2016 The Pragmatic Programmers, LLC. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the prior consent of the publisher. Printed in the United States of America. ISBN-13: 978-1-68050-126-1 Encoded using the finest acid-free high-entropy binary digits. Book version: P1.0—January 2016 www.it-ebooks.info
📄 Page 7
Contents Acknowledgments . . . . . . . . . . . ix Introduction . . . . . . . . . . . . . xi 1. Create a Great-Looking Login with Bootstrap and Devise . . 1 Setting Up Devise for Authentication 2 Installing Bootstrap with Bower 10 Styling the Login and Registration Forms 16 Validating Registration 22 Next: Using Postgres to Make Our Login More Secure 23 2. Secure the Login Database with Postgres Constraints . . 25 Exposing the Vulnerability Devise and Rails Leave Open 25 Prevent Bad Data Using Check Constraints 26 Why Use Rails Validations? 31 Next: Using Postgres Indexes to Speed Up a Fuzzy Search 32 3. Use Fast Queries with Advanced Postgres Indexes . . . 33 Implementing a Basic Fuzzy Search with Rails 34 Understanding Query Performance with the Query Plan 45 Indexing Derived and Partial Values 46 Next: Better-Looking Results with Bootstrap’s List Group 50 4. Create Clean Search Results with Bootstrap Components . 51 Creating Google-Style Search Results Without Tables 52 Paginating the Results Using Bootstrap’s Components 57 Next: Angular! 60 5. Build a Dynamic UI with AngularJS . . . . . . . 61 Configuring Rails and Angular 62 Porting Our Search to Angular 65 www.it-ebooks.info
📄 Page 8
Changing Our Search to Use Typeahead 79 Next: Testing 81 6. Test This Fancy New Code . . . . . . . . . 83 Installing RSpec for Testing 84 Testing Database Constraints 87 Running Headless Acceptance Tests in PhantomJS 91 Writing Unit Tests for Angular Components 103 Next: Level Up on Everything 117 7. Create a Single-Page App Using Angular’s Router . . . 119 Using Angular’s Router for User Navigation 121 Serving Angular Templates from the Asset Pipeline 124 Adding a Second View and Controller to Our Angular App 127 Next: Design Using Grids 135 8. Design Great UIs with Bootstrap’s Grid and Components . 137 The Grid: The Cornerstone of a Web Design 138 Using Bootstrap’s Grid 140 Adding Polish with Bootstrap Components 146 Next: Populating the View Easily and Efficiently 150 9. Cache Complex Queries Using Materialized Views . . . 151 Understanding the Performance Impact of Complex Data 152 Using Materialized Views for Better Performance 160 Keeping Materialized Views Updated 165 Next: Combining Data with a Second Source in Angular 169 10. Asynchronously Load Data from Many Sources . . . . 171 Understanding How Asynchronous Requests Work 172 Using Angular-Resource to Connect to Rails 175 Nesting Controllers to Organize Code 180 Using Bootstrap’s Progress Bar When Data Is Loading 183 Passing Data Between Controllers 186 Testing Controllers That Use Angular-Resource 189 Next: Sending Changes Back to the Server 191 11. Wrangle Forms and Validations with Angular . . . . 193 Managing Client-Side State with Bindings 194 Validating User Input with Angular Forms 195 Styling Invalid Fields with Bootstrap 200 Saving Data Back to the Server 205 Contents • vi www.it-ebooks.info
📄 Page 9
Understanding the Role of Rails Validators 209 Next: Everything Else 211 12. Dig Deeper . . . . . . . . . . . . . 213 Unlocking More of Postgres’s Power 213 Leveling Up with Angular 225 Getting Everything Out of Bootstrap 234 A1. Full Listing of Customer Detail Page HTML . . . . . 249 A2. Creating Customer Address Seed Data . . . . . . 253 Bibliography . . . . . . . . . . . . 257 Index . . . . . . . . . . . . . . 259 Contents • vii www.it-ebooks.info
📄 Page 10
Acknowledgments I’d like to first thank my wife Amy, who gave me the encouragement and space to spend time every morning writing this book. I’d also like to thank my editor, Fahmida Rashid, who managed to take what started as a functional requirements document for a customer service appli- cation and helped me turn it into a useful book. I’d further like to thank the many people who reviewed the in-progress book, including Chris Hoffman, David McClain, J. Daniel Ashton, Jacob Chae, John Cater, Maricris Nonato, Matthew Oldham, Nell Shamrell, Nigel Lowry, Simeon Willbanks, and Jeremy Frens (who had particular insights that I hope I’ve reflected well). And a huge thanks to the various readers who pointed out errors in the beta version of the book (including some rather embarrassing omissions): Andrea Bufalo Riva, Bradford Baker, Brent Nordquist, C. R. Myers, Chris McCann, Harri Jauri, J. Daniel Ashton, Jamie Finlay, Jesus Alc, John Lyons, Michael Pope, Narongsak Jirajaruwong, Nick Clyde, Patrick Joyce, Russ Martin, Sernin van de Krol, Stephen Lloyd, and Volker Wiegand. Finally, I’d like to thank the contributors to the software you’re learning about in this book. The people who have given their free time to make Ruby, Rails, Postgres, Angular, Bootstrap, PhantomJS, Teaspoon, Poltergeist, Devise, Capybara, RSpec, Angular-UI, Database Cleaner, Bower, and all other open source software are far too numerous to list here, but without their work, most developers would have a hard time doing their jobs. report erratum • discusswww.it-ebooks.info
📄 Page 11
Introduction Think about what part of an application you’re most comfortable working with. If you’re a Rails developer, there’s a good chance you prefer the back end, the Ruby code that powers the business logic of your application. What if you felt equally comfortable working with the database, such as tweaking queries and using advanced features of your database system? What if you were also comfortable working with the JavaScript and CSS necessary to make dynamic, usable, attractive user interfaces? If you had that level of comfort at every level of the application stack, you would possess great power as a developer to quickly produce high-quality software. Your ability to solve problems would not be restricted by the tools available via a single framework, nor would you be at the mercy of hard-to- find specialists to help you with what are, in reality, simple engineering tasks. The Rails framework encourages developers not to peer too closely into the database. Rails steers you away from JavaScript frameworks in favor of its sprinkling approach, where content is all rendered server-side. This book is going to open your eyes to all the things you can accomplish with your database, and set you on a path that includes JavaScript frameworks. With Rails acting as the foundation of what you do, you’ll learn how to embrace all other parts of the application stack. The Application Stack User Interface Middleware Data Store Many web applications—especially those built with Ruby on Rails—use a layered architec- ture that is often referred to as a stack, since most diagrams (like the one we use in this book) depict the layers as stacked blocks. Rails represents the middle of the stack, and is called middleware. This is where the core logic of your application lives. The bottom of the stack—the data store—is where the valuable data saved report erratum • discusswww.it-ebooks.info
📄 Page 12
and manipulated by your application lives. This is often a relational database management system (RDBMS). The top of the stack is the user interface. In a web application, this is HTML, CSS, and JavaScript served to a browser. Each part of the stack plays a crucial role in making software valuable. The data store is the canonical location of the organization’s most important asset—its data. Even if the organization loses all of its source code, as long as it retains its data, it can still survive. Losing all of the data, however, would be catastrophic. The top of the stack is also important, as it’s the way the users view and enter data. To the users, the user interface is the database. The difference between a great user interface and a poor one can mean the difference between happy users and irritated users, accurate data and unreliable data, a successful product and a dismal failure. What’s left is the part of the stack where most developers feel most comfort- able: the middleware. Poorly constructed middleware is hard to change, meaning the cost of change is high, and thus the ability of the organization to respond to changes is more difficult. Each part of the stack plays an important role in making a piece of software successful. As a Rails developer, you have amassed many techniques for making the middleware as high quality as you can. Rails (and Ruby) makes it easy to write clean, maintainable code. Digging deeper into the other two parts of the stack will have a great benefit for you as a developer. You’ll have more tools in your toolbox, making you more effective. You’ll also have a much easier time working with specialists, when you do have access to them, since you’ll have a good grasp of both the database and the front end. That’s what you’ll learn in this book. When you’re done, you’ll have a holistic view of application development, and you’ll have a new and powerful set of tools to augment your knowledge of Rails. With this holistic view, you can build seemingly complex features easily, sometimes even trivially. You’ll learn PostgreSQL, AngularJS, and Bootstrap, but you can apply many of the lessons here to other data stores, JavaScript libraries, and CSS frameworks. In addition to seeing just how powerful these specific tools can be, you’re going to be emboldened to think about writing software beyond what is provided by Rails. Introduction • xii report erratum • discusswww.it-ebooks.info
📄 Page 13
PostgreSQL, Angular, and Bootstrap: The Missing Parts of Our Stack If all you’ve done with your database is create tables, insert data, and query it, you’re going to be excited when you see what else you can do. Similarly, if all you’ve done with your web views is sprinkle some jQuery calls to your server-rendered HTML, you’ll be amazed at what you can do with very little code when you have a full-fledged JavaScript framework. Lastly, if you’ve been hand-rolling your own CSS, a framework like Bootstrap will make your life so much simpler, and your views will look and feel so much better. In this book, we’re going to focus on PostgreSQL (or simply Postgres) as our data store—the bottom of the stack—and AngularJS (or just Angular) with Bootstrap as our front end—the top of the stack. Each of these technologies is widely used and very powerful. You’re likely to encounter them in the real world, and they each underscore the sorts of features you can use to deliver great software outside of what you get with Rails. With these chosen technologies, our application stack looks like this: Angular Bootstrap Rails Postgres In each chapter, we’ll highlight the parts of the stack we’ll be focusing on and call out the various aspects of these technologies you’ll be learning. Not every chapter will focus on all parts of the stack, so at the start of each chapter, you’ll see a roadmap like this of what you’ll be learning: Angular Bootstrap Rails Postgres Focus of this chapter Focus of this chapter Not part of this chapter LOGIN Feature we're working on Form Styles Devise Aspects of the technologies we'll see in this chapter Let’s get a taste of what each has to offer, starting with PostgreSQL. report erratum • discuss The Application Stack • xiii www.it-ebooks.info
📄 Page 14
PostgreSQL PostgreSQL is an open source SQL database released in 1997. It supports many advanced features not found in other popular open source databases such as MySQL1 or commercial databases such as Microsoft SQL Server.2 Here are some of the features you’ll learn about (and I’ll show you how to use them with Rails): Check constraints You can create highly complex constraints on your table columns beyond what you get with not null. For example, you can require that a user’s email address be on a certain domain (which we’ll see in Chapter 2, Secure the Login Database, on page 25), that the state in a U.S. address be written exactly as two uppercase characters, or even that the state in the address must already be on a list of allowed state codes. While you can do this with Rails, doing it in the database layer means that no bug in your code, no existing script, no developer at a console, and no future program can put bad data into your database. This sort of data integrity just isn’t possible with Rails alone. Advanced indexing In many database systems, you can only index the values in the columns of the database. In Postgres, you can index the transformed values. For example, you can index the lowercased version of someone’s name so that a case-insensitive search is just as fast as an exact-match search. We’ll see this in Chapter 3, Use Fast Queries with, on page 33. Materialized views A database view is a logical table based on a SELECT statement. In Postgres a materialized view is a view whose contents are stored in an actual table—accessing a materialized view won’t run the query again like it would in a normal view. We’ll use one in Chapter 9, Cache Complex Queries, on page 151. Advanced data types Postgres has support for enumerated types, arrays, and dictionaries (called HSTOREs). In most database systems, you have to use separate tables to model these data structures. 1. https://www.mysql.com/ 2. http://www.microsoft.com/en-us/server-cloud/products/sql-server/ Introduction • xiv report erratum • discusswww.it-ebooks.info
📄 Page 15
Free-form JSON…that’s indexed Postgres supports a JSON data type, allowing you to store arbitrary data in a column. This means you can use Postgres as a document data store, or for storing data that doesn’t conform to a strong schema (something you’d otherwise have to use a different type of database for). And, by using the JSONB data type, you ensure that the JSON fields can be indexed, just like a structured table’s fields. Although you can serialize hashes to JSON in Rails using the TEXT data type, you can’t query them, and you certainly can’t index them. JSONB fields can interoperate with many systems other than Rails, and they provide great performance. AngularJS AngularJS3 is a JavaScript Model-View-Controller (MVC) framework created and maintained by Google (Angular bills itself as a Model-View-Whatever framework, but for this book, the Whatever will be a controller). Angular treats your view not as a static bit of HTML, but as a full-blown application. By adopting the mind-set that your front end is a dynamic, connected interface, and not a set of static pages, you open up many new possibilities. Angular provides powerful tools for organizing your code and lets you structure your markup to create intention-revealing, testable, manageable front-end code. It doesn’t matter how small or large the task—as your UI gets more complex, Angular scales much better than something more basic like jQuery. As an example, consider showing and hiding a section of the DOM using jQuery. You might do something like this: jquery_example.html <section> <p>You currently owe: $123.45</p> <button class="reveal-button">Show Details</button> <ul style="display: none" class="details"> <li>Base fee: $120.00</li> <li>Taxes: $3.45</li> </ul> </section> <script> $(".reveal-button").click(function($event) { $(".details").toggle(); }); </script> 3. https://angularjs.org report erratum • discuss The Application Stack • xv www.it-ebooks.info
📄 Page 16
It’s not much code, but if you’ve ever done anything moderately complex, your markup and JavaScript becomes a soup of magic strings, classes starting with js-, and oddball data- elements. An Angular version of this might look like this: angular_example.html <section ng-app="account" ng-model="showDetails" ng-init="showDetails = false"> <p>You currently owe: $123.45</p> <button ng-click="showDetails = !showDetails">Show/Hide Details</button> <ul ng-if="showDetails"> <li>Base fee: $120.00</li> <li>Taxes: $3.45</li> </ul> </section> <script> var app = angular.module("account",[]); </script> Here, the view isn’t just a description of static content, but a clear indication of how it should behave. Intent is obvious—you can see how this works without knowing the underlying implementation—and there’s a lot less code. This is what a higher-level of abstraction like Angular gives you that would otherwise be a mess with jQuery or just plain JavaScript. Unlike Postgres—where there are very few comparable open source alternatives that match its features and power—there are many JavaScript frameworks comparable to Angular. Many of them are quite capable of handling the fea- tures we’ll cover in this book. We’re using Angular for a few reasons. First, it’s quite popular, which means you can find far more resources online for learning it, including deep dives beyond what we’ll get to here. Second, it allows you to compose your front end similarly to how you compose your back end in Rails, but it’s flexible enough to allow you to deviate later if you need to. If you’ve never done much with JavaScript on the front end, or if you’re just used to jQuery, you’ll be pleasantly surprised at what Angular gives you: Clean separation of code and views Angular models your front end as an application with its own routes, controllers, and views. This makes organizing your JavaScript easy and tames a lot of complexity. Introduction • xvi report erratum • discusswww.it-ebooks.info
📄 Page 17
Unit testing from the start Testing JavaScript—especially when it uses jQuery—has always been a challenge. Angular was designed from the start to make unit testing your JavaScript simple and convenient. Clean, declarative views Angular views are just HTML. Angular adds special attributes called directives that allow you to cleanly connect your data and functions to the markup. You won’t have inline code or scripts, and a clear separation exists between view and code. Huge ecosystem Because of its popularity, there’s a large ecosystem of components and modules. Many common problems have a solution in Angular’s ecosystem. It’s hard to fully appreciate the power of a JavaScript framework like Angular without using it, but we’ll get there. We’ll turn a run-of-the-mill search feature into a dynamic, asynchronous live search, with very little code. Bootstrap Bootstrap4 is a CSS framework created by Twitter for use in their internal applications. A CSS framework is a set of CSS classes you apply to markup to get a particular look and feel. Bootstrap also includes components, which are classes that, when used on particular HTML elements in particular ways, produce a distinct visual artifact, like a form, a panel, or an alert message. The advantage of a CSS framework like Bootstrap is that you can create full- featured user interfaces without writing any CSS. Why be stuck with an ugly and hard-to-use form like this? By just adding a few classes to some elements, you can have something pol- ished and professional like this instead: 4. http://getbootstrap.com report erratum • discuss The Application Stack • xvii www.it-ebooks.info
📄 Page 18
In the next chapter we’ll do this to the login and registration forms provided by the Devise gem. We’ll have a great-looking user sign-up and sign-in expe- rience, without writing any CSS. Bootstrap includes a lot of CSS for a lot of different occasions. Typography Just including Bootstrap in your application and using semantic HTML will result in pleasing content with good general typography. Grid Bootstrap’s grid makes it easy to lay out complex, multicolumn compo- nents. It can’t be overstated how important and powerful this is. Form styles Styling good-looking forms can be difficult, but Bootstrap provides many CSS classes that make it easy. Bootstrap-styled forms have great spacing and visual appeal, and feel cohesive and inviting to users. Components Bootstrap also includes myriad components, which are CSS classes that, when applied to particular markup, generate a visual component, like a styled box or alert message. These components can be great inspiration for solving simple design problems. It’s important to note that Bootstrap is not a replacement for a designer, nor are all UIs created with Bootstrap inherently usable. There are times when a specialist in visual design, interaction design, or front-end implementation is crucial to the success of a project. But for many apps, you don’t need these specialists (they are very hard to find when you do). Bootstrap lets you produce a professional, appealing user interface without them. Bootstrap also lets you realize visual designs that might seem difficult to do with CSS. In Chapter 4, Create Clean Search Results, on page 51 and Chapter 8, Design Great UIs with, on page 137, you’ll see just how easy it is to create a customized UI without writing CSS, all thanks to Bootstrap. Even if you have a designer or front-end specialist, the skills you’ll learn by using Bootstrap will still apply—your front-end developer isn’t going to write every line of markup and CSS. They are going to hand you a framework like Bootstrap that enables you to do many of the things we’ll do in this book. Now that you’ve gotten a taste of what we’ll be covering, let’s talk about how you’re going to learn it. Introduction • xviii report erratum • discusswww.it-ebooks.info
📄 Page 19
Postgres, Angular, and Bootstrap—At the Same Time If you’ve already looked at the table of contents, you’ll see that this book isn’t divided into three parts—one for Postgres, one for Angular, and one for Bootstrap. That’s not how a full-stack developer approaches development. A full-stack developer is given a problem to solve and is expected to bring all forces to bear in solving it. For example, if you’re implementing a search, and it’s slow, you’ll consider both creating an index in the database as well as performing the search with Ajax calls to create a more dynamic and snappy UI. You should use features at every level of the stack to get the job done. SEARCH FEATURE Angular Bootstrap Rails Postgres Search Form Search Logic Ajax Calls Results View Indexes This holistic approach is how you’re going to learn these technologies. We’ll build a Rails application together, adding features one at a time. These features will demonstrate various aspects of the technologies we’re using. To keep things simple, each chapter will focus on a single technology, and we’ll complete features over several chapters. For example, in the next chapter we’ll set up a simple registration system for our application and use Bootstrap to style the views. In Chapter 2, Secure the Login Database, on page 25, we’ll continue the feature but focus on using Postgres to add extra security at the database layer. This will allow us to see each feature evolve as we bring in relevant parts of the application stack. This will give you the confidence to do the same for other features that you build in your own apps. It’s also worth emphasizing the role of Rails in all of this. Although Rails doesn’t have built-in APIs for using Postgres’s advanced features, nor support for Angular’s way of structuring code, it doesn’t outright prevent our using them. And Rails is a great middleware; probably one of the best. report erratum • discuss Postgres, Angular, and Bootstrap—At the Same Time • xix www.it-ebooks.info
📄 Page 20
So, in addition to learning Postgres, Angular, and Bootstrap, you’re going to learn how to get them working with Rails. You’ll see not just how to create check constraints on columns in our tables, but how to do that from a Rails migration. And you won’t just learn how to style Angular components with Bootstrap—you’ll do it using assets served up by the asset pipeline. Let’s learn about the Rails application that we’ll be building in this book. Shine, the Application We’ll Build In this book we’ll create and add features to a Rails application. We’re creating this application for the customer service agents at the hypothetical company where we work. Our company has a public website that its customers use, but we want a separate application for the customer service agents. You’ve probably seen or heard about internal-facing apps like this. Perhaps you’ve even worked on one (most software is internally facing). The application will be called Shine (since it allows our great customer service to shine through to our customers). The features that we’ll build for this application involve searching for, viewing, and manipulating customer data. For example, we’ll allow the user to search for customers. Googlehttp://shine.example.com/customers/1234 Shine: Customer 1234 Bob Bob Jones bobert1234 bjones18@somewhere.net JOINED 10/12/2014 Darrell Bobbins dbob bjones18@somewhere.net JOINED 1/13/2014 Bobby Smith bbysmith bjones18@somewhere.net JOINED 10/12/2014 And they can click through and view or edit a customer’s data. Introduction • xx report erratum • discusswww.it-ebooks.info
The above is a preview of the first 20 pages. Register to read the complete e-book.

💝 Support Author

0.00
Total Amount (¥)
0
Donation Count

Login to support the author

Login Now
Back to List