Obie Fernandez, Kevin Faustino — «The Rails 4

Total Page:16

File Type:pdf, Size:1020Kb

Obie Fernandez, Kevin Faustino — «The Rails 4 The Rails 4 Way Obie Fernandez, Kevin Faustino and Vitaly Kushner This book is for sale at http://leanpub.com/tr4w This version was published on 2014-06-03 This is a Leanpub book. Leanpub empowers authors and publishers with the Lean Publishing process. Lean Publishing is the act of publishing an in-progress ebook using lightweight tools and many iterations to get reader feedback, pivot until you have the right book and build traction once you do. ©2013 - 2014 Obie Fernandez, Kevin Faustino and Vitaly Kushner Tweet This Book! Please help Obie Fernandez, Kevin Faustino and Vitaly Kushner by spreading the word about this book on Twitter! The suggested tweet for this book is: I just bought the beta release of The Rails 4 Way The suggested hashtag for this book is #tr4w. Find out what other people are saying about the book by clicking on this link to search for this hashtag on Twitter: https://twitter.com/search?q=#tr4w Taylor, your hard work and dedication to your craft is an inspiration to me every day. I love you… Contents Foreword ................................................... ii Foreword (to The Rails 3 Way) ....................................... iii Foreword (to The Rails Way) ........................................ v Acknowledgments .............................................. vi About the Authors .............................................. vii Obie Fernandez .............................................. vii Kevin Faustino .............................................. vii Introduction ................................................. viii About This Book ............................................. viii Recommended Reading and Resources ................................. ix Goals ................................................... x Prerequisites ................................................ xi Required Technology ........................................... xi 1 Rails Environments and Configuration ................................ 1 1.1 Bundler ............................................... 1 1.2 Startup and Application Settings ................................. 8 1.3 Development Mode ........................................ 16 1.4 Test Mode .............................................. 20 1.5 Production Mode .......................................... 21 1.6 Configuring a Database ...................................... 24 1.7 Configuring Application Secrets .................................. 26 1.8 Logging ............................................... 27 2 Routing .................................................. 34 2.1 The Two Purposes of Routing ................................... 34 2.2 The routes.rb File .......................................... 35 2.3 Route Globbing ........................................... 47 2.4 Named Routes ........................................... 48 2.5 Scoping Routing Rules ....................................... 53 2.6 Listing Routes ........................................... 55 2.7 Conclusion ............................................. 56 CONTENTS 3 REST, Resources, and Rails ....................................... 57 3.1 REST in a Rather Small Nutshell ................................. 57 3.2 Resources and Representations .................................. 58 3.3 REST in Rails ............................................ 58 3.4 Routing and CRUD ......................................... 59 3.5 The Standard RESTful Controller Actions ............................ 62 3.6 Singular Resource Routes ..................................... 65 3.7 Nested Resources .......................................... 66 3.8 Routing Concerns ......................................... 70 3.9 RESTful Route Customizations .................................. 71 3.10 Controller-Only Resources ..................................... 75 3.11 Different Representations of Resources .............................. 77 3.12 The RESTful Rails Action Set ................................... 79 3.13 Conclusion ............................................. 83 4 Working with Controllers ....................................... 85 4.1 Rack ................................................. 85 4.2 Action Dispatch: Where It All Begins ............................... 88 4.3 Render unto View… ........................................ 91 4.4 Additional Layout Options ..................................... 99 4.5 Redirecting ............................................. 100 4.6 Controller/View Communication ................................. 103 4.7 Action Callbacks .......................................... 104 4.8 Streaming .............................................. 109 4.9 Variants ............................................... 114 4.10 Conclusion ............................................. 115 5 Working with Active Record ...................................... 117 5.1 The Basics ............................................. 117 5.2 Macro-Style Methods ....................................... 118 5.3 Defining Attributes ......................................... 121 5.4 CRUD: Creating, Reading, Updating, Deleting . 125 5.5 Database Locking ......................................... 138 5.6 Where Clauses ........................................... 141 5.7 Connections to Multiple Databases in Different Models . 152 5.8 Using the Database Connection Directly ............................. 153 5.9 Other Configuration Options ................................... 157 5.10 Conclusion ............................................. 157 6 Active Record Migrations ........................................ 159 6.1 Creating Migrations ........................................ 159 6.2 Data Migration ........................................... 172 6.3 schema.rb ............................................. 174 6.4 Database Seeding .......................................... 174 6.5 Database-Related Rake Tasks ................................... 175 6.6 Conclusion ............................................. 179 CONTENTS 7 Active Record Associations ....................................... 180 7.1 The Association Hierarchy ..................................... 180 7.2 One-to-Many Relationships .................................... 181 7.3 The belongs_to Association .................................... 189 7.4 The has_many Association ..................................... 197 7.5 Many-to-Many Relationships ................................... 205 7.6 One-to-One Relationships ..................................... 215 7.7 Working with Unsaved Objects and Associations . 219 7.8 Association Extensions ....................................... 220 7.9 The CollectionProxy Class .................................... 221 7.10 Conclusion ............................................. 222 8 Validations ................................................ 224 8.1 Finding Errors ........................................... 224 8.2 The Simple Declarative Validations ................................ 224 8.3 Common Validation Options ................................... 234 8.4 Conditional Validation ....................................... 236 8.5 Short-form Validation ....................................... 238 8.6 Custom Validation Techniques .................................. 239 8.7 Skipping Validations ........................................ 242 8.8 Working with the Errors Hash ................................... 242 8.9 Testing Validations with Shoulda ................................. 243 8.10 Conclusion ............................................. 244 9 Advanced Active Record ........................................ 245 9.1 Scopes ................................................ 245 9.2 Callbacks .............................................. 250 9.3 Calculation Methods ........................................ 259 9.4 Single-Table Inheritance (STI) ................................... 261 9.5 Abstract Base Model Classes .................................... 267 9.6 Polymorphic has_many Relationships ............................... 268 9.7 Enums ............................................... 272 9.8 Foreign-key Constraints ...................................... 274 9.9 Modules for Reusing Common Behavior ............................. 274 9.10 Modifying Active Record Classes at Runtime . 278 9.11 Using Value Objects ........................................ 280 9.12 Non-Persisted Models ....................................... 283 9.13 PostgreSQL enhancements ..................................... 285 9.14 Conclusion ............................................. 292 10 Action View ............................................... 293 10.1 Layouts and Templates ....................................... 293 10.2 Partials ............................................... 302 10.3 Conclusion ............................................. 308 11 All About Helpers ............................................ 309 CONTENTS 11.1 ActiveModelHelper ........................................ 309 11.2 AssetTagHelper .......................................... 315 11.3 AtomFeedHelper .......................................... 323 11.4 CacheHelper ............................................ 325 11.5 CaptureHelper ........................................... 325 11.6 CsrfHelper ............................................. 326 11.7 DateHelper ............................................. 327 11.8 DebugHelper ............................................ 333 11.9 FormHelper ............................................. 333 11.10 FormOptionsHelper .......................................
Recommended publications
  • The Rails™ 4 Way
    Praise for The Rails Way For intermediates and above, I strongly recommend adding this title to your tech- nical bookshelf. There is simply no other Rails title on the market at this time that offers the technical depth of the framework than The Rails™ 3 Way. — Mike Riley, Dr. Dobb’s Journal I highly suggest you get this book. Software moves fast, especially the Rails API, but I feel this book has many core API and development concepts that will be useful for a while to come. — Matt Polito, software engineer and member of Chicago Ruby User Group This book should live on your desktop if you’re a Rails developer. It’s nearly perfect in my opinion. — Luca Pette, developer The Rails™ 3 Way is likely to take you from being a haphazard poke-a- stick- at- it programmer to a deliberate, skillful, productive, and confi dent RoR developer. — Katrina Owen, JavaRanch I can positively say that it’s the single best Rails book ever published to date. By a long shot. — Antonio Cangiano, software engineer and technical evangelist at IBM psn-fernandez-all.indb i 5/9/14 10:07 AM This book is a great crash course in Ruby on Rails! It doesn’t just document the features of Rails, it fi lters everything through the lens of an experienced Rails developer— so you come out a pro on the other side. — Dirk Elmendorf, cofounder of Rackspace Inc. and Rails developer The key to The Rails Way is in the title. It literally covers the “way” to do almost everything with Rails.
    [Show full text]
  • Skimmer Tracker Building a Payment Card Skimmer Database
    Degree Final Project Bachelor Degree in Informatics Engineering Specialization in Software Engineering Skimmer Tracker Building a payment card skimmer database Arnau Buch Torrents Project Director: Nolen Scaife, Department of Computer Science, CU Boulder Internal examiner: Ernest Teniente, ESSI Department, FIB-UPC Defense date: 30th of June, 2020 Abstract With the rise of credit cards as an integral part of the economy, crime related to them has risen accordingly. One of the most common ways to steal credit card data is through skimmers in gas-pumps. The skimmer device consists of a simple PCB (printed circuit board), and it is inserted inside the gas-pump to steal consumer’s credit cards. Incurred costs due to fraud can go well into the thousands per person. Criminals install multiple skimmers across counties and states in the US. When skimmers are eventually discovered it is practically impossible for police to conduct a successful investigation on them. Police departments rarely collaborate on these sorts of cases that span different counties and states, which eliminates any possibility of them being solved. Skimmer Tracker is a web application that lets law enforcement agencies publish the skimmers they find. With this sharing of evidence we aim to group different skimmers and connect them as part of the same case through computer vision based analysis. Resum Amb l’auge de les targetes de crèdit com a part integral de l’economia, els delictes relacionats amb elles ha augmentat corresponentment. Una de les maneres més comunes de robar les dades de targetes de crèdit és a través de skimmers als sortidors de gasolina.
    [Show full text]
  • Ecosystems in Github and a Method for Ecosystem Identification Using
    Ecosystems in GitHub and a Method for Ecosystem Identification using Reference Coupling Kelly Blincoe, Francis Harrison and Daniela Damian Software Engineering Global InterAction Lab University of Victoria Victoria, BC, Canada Email: [email protected], [email protected], [email protected] Abstract—Software projects are not developed in isolation. To identify technical dependencies, we turn to cross- Recent research has shifted to studying software ecosystems, references on GitHub, a social code hosting service. GitHub communities of projects that depend on each other and are encourages collaboration between users both within and across developed together. However, identifying technical dependencies at the ecosystem level can be challenging. In this paper, we projects through its transparent interface and built-in social 1 propose a new method, known as reference coupling, for detecting features. With GitHub Flavored Markdown , when a user technical dependencies between projects. The method establishes cross-references another repository in a pull request, issue or dependencies through user-specified cross-references between commit comment a link to the other repository is automati- projects. We use our method to identify ecosystems in GitHub- cally created. This introduces a way for developers to bring hosted projects, and we identify several characteristics of the identified ecosystems. We find that most ecosystems are centered awareness across repositories. In this paper, we investigate around one project and are interconnected with other ecosystems. whether these cross-references indicate a technical dependency The predominant type of ecosystems are those that develop between the two repositories by examining a set of these tools to support software development. We also found that the cross-references.
    [Show full text]
  • ← Benjamin Fleischer's Resume
    Benjamin Fleischer Chicago, IL, United States M) 708-421-1699 http://benjaminfleischer.com SUMMARY: Active open-source software maintainer and contributor. Maintains or collaborates on tens of projects, including ActiveModelSerializers, SimpleCov, RubyGems guide, and RMagick. Has contributed to tens of others, including Rails, NodeJS, JSON:API, Kaminari, Homebrew, bcrypt-ruby, and Passenger. Core maintainer of ActiveModelSerializers, one of the most popular Ruby serialization libraries. Created the RubyGems guides security page PROFESSIONAL EXPERIENCE: Web Development Software Engineer – SwipeSense, Inc. – Chicago, IL, July 2015‑July 2017 Hand‑hygiene sensors and analytics to help healthcare institutions eliminate acquired infections. Ruby and Rails, Principal Developer: Responsible for API design, implementation, security, testing, and documentation. Improved development UX, such as by added headless Chrome testing. Prior to that, added qtchooser. Databases Management (MySQL/Postgres/Redshift): Schema design, query optimization, and index optimization. Created regular backups and easy restores that are regularly tested. ETL (Extract Transform Load) management. Created tooling for coding standards automation: Automated style enforcement, security scan, vulnerability scan, and library upgrades. Add Docker-backed database images on for continuous testing. Add datamart/analytics data to test and development environment. ECMAScript: Ember.js, React.js, Webpack. Amazon Web Services (AWS): CLI scripting for ENV versioning, creating resources, deploying resources, and starting/stopping servers by name Web Development Software Engineer – Springleaf Financial Services – Chicago, IL, November 2014‑May 2015 Created tooling for coding standards automation: Common Rails template, API controller base, API client base, worker configuration (including ActiveJob). Code coverage, security, and style via git hooks. (Essential before we had staging or CI). Improved team communication: Set up first chat server, wrote up onboarding documents, created employee directory.
    [Show full text]
  • Catalog CALIFORNIA
    Catalog CALIFORNIA January 1 - December 31, 2021 Revision Date: January 13, 2021 www.appacademy.io 825 Battery St 3rd Floor, San Francisco, CA 94111 (415) 417 - 1991 APP ACADEMY CATALOG 2021 | CALIFORNIA Page 2 of 56 Table of Contents Introduction 2 Facilities and Learning Resources 3 Programs and Objectives 4 Soware Engineering Program: Full-Time In-Person 4 Soware Engineering Track: Full-Time Online 10 Bootcamp Prep In-Person & Bootcamp Prep Online 14 Admissions Policies and Procedures 17 Overview 17 Soware Engineering Program: Full-Time In-Person 22 Soware Engineering Track: Full-Time Online 22 Bootcamp Prep In-Person & Bootcamp Prep Online 23 Academic Policies 24 Student Services 31 Student Rights and Grievance Procedure 33 Cancellation, Withdrawal, and Refund Policies 39 Tuition and Fees 42 Bootcamp Prep In-Person 42 Bootcamp Prep Online 42 Soware Engineering Program: Full-Time In-Person 43 Soware Engineering Track: Full-Time Online 48 Faculty 52 Further Information 53 825 Battery St 3rd Floor, San Francisco, CA 94111 APP ACADEMY CATALOG 2021 | CALIFORNIA Page 3 of 56 Introduction Approval to Operate and Information App Academy is a private institution. App Academy is approved to operate by the California Bureau of Private Postsecondary Education. Approved to operate means compliance with state standards as set forth in the California Private Postsecondary Act of 2009 (California Education Code, Title 3, Division 10, Part 59, Chapter 8) and Division 7.5 of Title 5 of the California Code of Regulations. Location of Classes All California classes are conducted at 825 Battery St 3rd Floor, San Francisco, CA 94111 (tel: +1 415 417 1991).
    [Show full text]
  • Types/Bluebird
    @types/bluebird MIT https://www.npmjs.com/package/@types/bluebird @types/body-parser MIT https://www.npmjs.com/package/@types/body-parser @types/chai MIT https://www.npmjs.com/package/@types/chai @types/express MIT https://www.npmjs.com/package/@types/express @types/express-serve-static-core MIT https://www.npmjs.com/package/@types/express-serve-static-core @types/form-data MIT https://www.npmjs.com/package/@types/form-data @types/geojson MIT https://www.npmjs.com/package/@types/geojson @types/js-yaml MIT https://www.npmjs.com/package/@types/js-yaml @types/lodash MIT https://www.npmjs.com/package/@types/lodash @types/mime MIT https://www.npmjs.com/package/@types/mime @types/moment-range MIT https://www.npmjs.com/package/@types/moment-range @types/node MIT https://www.npmjs.com/package/@types/node @types/node-statsd MIT https://www.npmjs.com/package/@types/node-statsd @types/react MIT https://www.npmjs.com/package/@types/react @types/react-dom MIT https://www.npmjs.com/package/@types/react-dom @types/react-transition-group MIT https://www.npmjs.com/package/@types/react-transition-group @types/recompose MIT https://www.npmjs.com/package/@types/recompose @types/request MIT https://www.npmjs.com/package/@types/request @types/sequelize MIT https://www.npmjs.com/package/@types/sequelize @types/serve-static MIT https://www.npmjs.com/package/@types/serve-static @types/validator MIT https://www.npmjs.com/package/@types/validator aasm MIT https://rubygems.org/gems/aasm abab ISC https://www.npmjs.com/package/abab abbrev ISC http://github.com/isaacs/abbrev-js
    [Show full text]
  • 3.2.3.2 AWS Elastic Beanstalk Section ………………………… 34 4 Project Cloudm from the Point of View of a User .……….……………..…… 37 4.1 End Users Panel ……………………………………………………………
    Deployment and migration of business services in the cloud Autor: Bartosz Ignaczewski Director: Jose Luis Vazquez-Poletti Erasmus programme 2016-2017 !1 Table of contents 1 Introduction .…………………………………………………………………… 5 1.1 Issue of the work ……..………………………..……………………….. 5 1.2 Scope and objective of the work ………..………………………………. 6 1.3 Structure of the work ……………………………………………………. 7 2 Deployment and migration of business services in the cloud .………………. 8 2.1 Cloud computing overview ………………………………………………8 2.1.1 Cloud computing definition ………………………………………. 8 2.1.2 Why do we need cloud computing? ………………………………. 9 2.1.3 Cloud computing characteristics …………………………………..11 2.1.4 Cloud computing deployment models …………………………….14 2.1.4.1 Public cloud …………………………………………….. 14 2.1.4.2 Private cloud ……………………………………………. 15 2.1.4.3 Community cloud ………………………………………. 15 2.1.4.4 Hybrid cloud ……………………………………………. 15 2.1.5 Cloud computing service models ………………………………… 16 2.1.5.1 Infrastructure as a Service ……………………………….17 2.1.5.2 Platform as a Service …………………………………….18 2.1.5.3 Software as a Service …………………………………….18 2.2 Overview of existing solutions ……….……………….…………………19 2.2.1 Deployment ………………………………………………………..19 2.2.1.1 Infrastructure as a Service ……………………………… 20 2.2.1.2 Platform as a Service …………………………………….21 2.2.2 Migration …………………………………………………………..22 3 Project CloudM ………………………………………………..………………..24 3.1 Project overview …………………………………………………………24 3.1.1 End users panel …………………………………………………….24 3.1.2 Administrator panel ………………………………………………..25 3.1.3 Sample use cases …………………………………………………..28 3.2 Tools, solutions and technologies used in the project ………………….. 29 3.2.1 Overview …………………………………………………………. 29 !2 3.2.1.1 Ruby on Rails framework ……………………………… 29 3.2.1.2 Communication with Amazon Web Services ………….
    [Show full text]
  • Open Source Used in AMP Operations Admin Console 2.1
    Open Source Used In AMP Operations Admin Console 2.1 Cisco Systems, Inc. www.cisco.com Cisco has more than 200 offices worldwide. Addresses, phone numbers, and fax numbers are listed on the Cisco website at www.cisco.com/go/offices. Text Part Number: 78EE117C99-1070844267 Open Source Used In AMP Operations Admin Console 2.1 1 This document contains licenses and notices for open source software used in this product. With respect to the free/open source software listed in this document, if you have any questions or wish to receive a copy of any source code to which you may be entitled under the applicable free/open source license(s) (such as the GNU Lesser/General Public License), please contact us at [email protected]. In your requests please include the following reference number 78EE117C99-1070844267 Contents 1.1 tilt 1.4.1 1.1.1 Available under license 1.2 jquery-rails 4.3.1 1.2.1 Available under license 1.3 method-source 0.8.2 1.3.1 Available under license 1.4 bootstrap-sass 2.2.1.1 1.4.1 Available under license 1.5 multi-json 1.12.1 1.5.1 Available under license 1.6 globalid 0.4.0 1.6.1 Available under license 1.7 ruby-timecop 0.8.0 1 1.7.1 Available under license 1.8 font-awesome-rails 4.6.3.0 1.8.1 Available under license 1.9 safe-yaml 1.0.4 1.9.1 Available under license 1.10 arel 6.0.4 1.10.1 Available under license 1.11 rest-client 1.8.0 1.11.1 Available under license 1.12 httpcookie 1.0.3 1.12.1 Available under license 1.13 openssl 2.0.3 1.13.1 Available under license Open Source Used In AMP Operations Admin
    [Show full text]
  • SHAI COLEMAN I'm Currently Not Considering New Opportunities Until Further Notice
    SHAI COLEMAN I'm currently not considering new opportunities until further notice. PROFESSIONAL PROFILE: A 360° expertise in a wide range of technical roles covering the full stack: polyglot development, business analysis, devops, system administration, front end and back end development, database development and administration, performance, security and agile project management. Up to date with the latest trends and best practices in the industry. Lifelong passion for technology. Working in tech since 1992. WORK HISTORY: Nov/2018 – Cash Analytics (enterprise cash flow forecasting) – senior developer Present: Software developer Dec/2017 – Full Health Medical (preventative healthcare startup) – senior back-end developer, devops Mar/2018: Rails development (Rails/MongoDB/RSpec/Capistrano). Technical debt cleanup, improved project health (software upgrades, performance, security, code quality, testing, code cleanup, documentation). Migrated legacy infrastructure to Ansible, Ubuntu 16.04, Capistrano 3, Envoy Proxy & AWS. Jun/2015 – Storyful (social media content agency) – senior back-end developer, reliability engineer Nov/2017: Mentoring and advising a team of up to 8 developers and beyond. Implemented best practices, code reviews and pair programming. Rails development (Rails/PostgreSQL/ElasticSearch/Agile/Scrum/OOP/RSpec/Capistrano/ Sidekiq/NewRelic) and a bit of Angular/EmberJS. Reworked a social media content discovery app from legacy prototype to product. Handled 50x scale increase and reduced downtime 10x. Architected a real time social network monitoring tool to handle 20x more data (Rails/Redis). Rearchitected a video archiving tool to collect virality metrics across various platforms. Developed a distributed peeking MITM proxy (Go/AWS/Terraform/Docker/Elastic Stack). Migrated various legacy apps to Rails 5. Migrated infrastructure to AWS, Ubuntu 16.04, systemd, Capistrano 3, PostgreSQL 9.6, etc.
    [Show full text]
  • Third Party License Agreements
    Third party license agreements In this document you can find all third party libraries used by PlanRadar GmbH in its products and their respective License Agreements. iOS App TPKeyboardAvoiding Licence (Zlib) Copyright (c) 2013 Michael Tyson This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. This notice may not be removed or altered from any source distribution. KKPinCodeTextField (ios_pinCodeTextField) Copyright (c) 2018 Amirzhan [email protected] Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
    [Show full text]
  • Timeline Project 1
    RUNNING HEAD: TIMELINE PROJECT 1 BUILDING AN OPEN SOURCE SOCIAL MEDIA AGGREGATION TIMELINE A Capstone Project Submitted to Southern Utah University in partial fulfillment of the requirements for the degree of Master of Arts in Professional Communication January 2014 By Justin Aiken Capstone Committee: Jon Smith, Ph.D., Committee Chair Lance Jackson, M.A. Lindsey Harvell, Ph.D. TIMELINE PROJECT 2 APPROVAL PAGE The undersigned, appointed by the dean of the Humanities and Social Science, have examined the thesis entitled Building An Open Source Social Media Aggregation Timeline Presented by Justin Aiken a candidate for the degree of Master of Arts in Professional Communication and hereby that, in our opinion, is worthy of acceptance. ____________________________________________ Chair of Committee – Jon Smith, Ph.D. ____________________________________________ Committee Member – Lindsey Harvell, Ph.D. ____________________________________________ Committee Member – Lance Jackson, M.A. TIMELINE PROJECT 3 Abstract An ever growing number of web services and social media networks allow one to post a lot of content in to many different websites and services; however, there is no simple way to chronologically aggregate the content – especially not in a space controlled by the user. Relying on a site or service to present the user’s data through their interface allows for too much noise and muddies the user’s message. In response, this project built an open source, expandable timeline that pulls in a user's content from various places on the web,
    [Show full text]