fabiochiu/medium-articles huggingface dataset:
Bring Your Own Images (BYOI) for Rails
Tags: Rails, Cloud 66, Ruby on Rails

We were pleased to release Bring Your Own Images (BYOI) for Rails in our Beta program back in July. Today we are happy to graduate this feature to general availability.

BYOI Overview

Bring Your Own Images (BYOI) allows developers to spin up new servers for the applications that are based on custom server images rather than on a generic Ubuntu server.

Bring Your Own Images benefits for Rails

BYOI enhances your Rails applications in the following ways:

Because custom server images can have all the libraries and components required by your application pre-installed, such as languages and frameworks, they can dramatically reduce the time for a new server to be provisioned.

You can use these images to quickly start servers on supported cloud providers. This means you can scale up dramatically faster. It also makes it possible to freeze a server (with a cloud image or snapshot) and create another server based on that image.

It gives developers the flexibility to choose a server that fits better in their infrastructure, rather than relying on generic Ubuntu servers. This allows you to maintain exotic or non-standard configurations more easily.

Note: For production environments make sure that the images you have are up-to-date with the base components of your live servers, such as language or framework.

Our launch cloud partners for Bring Your Own Images are:

AWS

Google Compute Engine

DigitalOcean

…with more on their way.
Installing Rails on the Chromebook
By: Jacob Kenny
Tags: Rails

Last week I wrote a little bit about my goal of configuring React to work with my chromebook. Although it runs very slowly, it does run, and all told it was easier to set up than I anticipated. This week however, I decided that I wanted to take the React application that I had been working on, and turn it into a full stack application. In order for me to do that, there certainly options, but in the name of sticking to what I know, I decided that the back end should be created with Rails — which it turns out I definitely don’t remember as well as I might have hoped!

The first thing that I needed to take care of was installing Ruby on the machine. I didn’t really know too much about what I was doing, but I followed the instructions at https://www.ruby-lang.org/en/documentation/installation/ for a Debian distribution of Linux. I felt like the next step would be to install the Rails gem. However, when I attempted the command: “gem install rails” it was unsuccessful. After some careful consideration and reading, I found other users who had similar issues. It seems that it is certainly possible to install Rails in this way, but it involves some serious messing around with configuration files — something that I am not really up for. So now what? I continued reading, and found a suggestion to utilize a version manager. Apparently, doing so would allow me to bypass the manual configuration of some hard-to-find files, and from what I could tell there are two good options — rbenv, and RVM (short for Ruby version manager).

I started off by uninstalling the Ruby version that I had originally installed, and then by trying rbenv — I followed all the steps (to the best of my knowledge), but when it came time to actually install the latest version of Ruby, the command would just cause my terminal to freeze up, and eventually it would terminate the command. I’m not sure if this was because of something that I did, or perhaps some issue with the program, but I felt like I was spending too much time on this, and decided to uninstall the rbenv program, and try to get things going with RVM. Thanfully, this turned out to be the solution. Using the rvm command line interface, I was able to install the newest version of Ruby, as well as the Rails gem.

At this point I was able to create a new Rails project, but I’m sure that there will still be more configuration to take care of. For example, I can tell already that I’m going to have some trouble with getting Postgres connected to the app — but I think that will have to be a problem for future me.

https://metova.com/choosing-a-ruby-version-management-tool-rbenv-vs-rvm/#:~:text=RVM%20overrides%20the%20cd%20shell,using%20shims%20to%20execute%20commands.

https://forum.theodinproject.com/t/gem-install-rails-solved/15587
Model 和table的關係到底是什麼？
By: Mino Chen
Tags: Rails, Migration, Table, Model

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
Hot Keys, Read all About it!
By: Sarah Ridge
Tags: Hotkeys, Accessibility, Keyboarding, Keyboard Shortcuts, Rails

Go away Mouse!

Backstory

I recently purchased the ultimate hacking keyboard. Currently, the trackball module is still in design. In a way, this is a good thing. I am now inspired to really use the keyboard as designed and move away from a traditional mouse. The caps lock is replaced with mouse as a different way of navigating. For example, hold or double tap mouse and move the arrows (using the remapped arrow keys). This may sound like a steep learning curve already. To be honest, this is the first ergo split mechanical whatever other term keyboard I have tried that is the most intuitive and well thought out. The parts that seem like a steep learning curve are actually not because of the design.

What I realized is there are many key bindings or ways of moving around a computer that do not actually require a mouse. The ultimate hacking keyboard made it more obvious and functional while still keeping the base layout of a standard keyboard the same. It is the first mechanical ergo keyboard I was able to use out of the box. Some of the other ergo keyboards are so customizable, I did not know where to begin and became stressed out trying to simply type my name. This keyboard is still customizable but I have found there were only two keys I needed to remap (swapping the placement of the fn and command keys). I did play around with making my own custom key bindings but that was more to test out the software. In which, the software works as expected and is easy to use.

Ok great, I’m making progress with this new keyboard and to be honest, every other keyboard is sub-standard to me at this point. I switched to a regular keyboard to feel the difference and it lasted less than 5 seconds.

I can admit, moving around the pointer using the keyboard and arrows can be a bit annoying. Even with the “speed booster” (I forget what it is called but it is the equivalent of faster scrolling speed), this keyboard makes me want to figure out how to get to things without needing the pointer. This journey has also exposed Accessibility to me in ways that I never thought I would care about.
Rails contact form with Postmark & deployed to Heroku with domain
By: Beatriz Longley
Tags: Contact Form, Tutorial, Heroku, Postmark, Rails

I have recently built a project that involved having a contact form for users to reach out to the company with any questions about their product and services.

To set it up I found myself having to jump between different articles, websites and tutorials to find all the information. My goal with this article is to perhaps help someone out there who wants to build a similar project, to find all the information in one place.

So here it is, my tutorial in 7 steps to build a rails app with a contact form which sends an automatic email using postmark, deployed into heroku with a domain.

Step 1 — Create a rails app with postgresql and push the project to GitHub

rails new contact-form --database=postgresql cd contact-form

hub create

git add .

git commit -m "new rails"

git push origin master

Step 2 — Generate Contact model and Contacts controller / Setup your routes

rails g model Contact name:string email:string topic:string message:text terms:boolean rails db:migrate rails g controller Contacts

Define your routes on routes.rb and add active record validations on contact.rb:

We will focus on the controller later on.

Step 3 — Additional configuration

I configured the assets using scss and added bootstrap to then be able to use simple form on my app.

Add the gem ‘simple-form’ to the Gemfile and:

bundle install

rails g simple_form:install --bootstrap

Step 4 — Generate Contact mailer

rails g mailer Contact

This is what your contact_mailer.rb would look like:

‘From’ is setup with the email address created with your domain.

This is what your application_mailer.rb would look like:

This is what your new_contact.html.erb would look like (this is the body of your email, written in html):

You are able to see what your email looks like locally by using rails s and accessing the following URL with the right path to the mailer method:

Step 5 — Complete the contacts_controller.rb and write & style your new.html.erb

Step 6 — Time to setup Postmark.
Handling MySQL Deadlocks with Counter Cache
By: Gowtham Rupavatharam
Tags: Deadlock, Counter Cache, Rails, MySQL

Rails counter_cache is quite helpful to find associated objects count in the belonging object efficiently.

But, it leads to Deadlocks while creating lots of associated records concurrently especially with MySQL. Unfortunately, deadlocks happen even for small numbers like 300–500 records.

As mentioned in this MySQL bug report this happens due to the Foreign Key Constraint, when an insert is executed on the associated table, a shared lock is requested on belonging table that leads to deadlocks when large number of inserts are triggered

How do we solve this? There are 2 approaches

1) Replace ActiveRecord counter_cache callback with our own. This makes the counter statement to get executed before insert without deadlocks

class User < ApplicationRecord

belongs_to :company before_create do

company.increment!(:users_count)

end

after_destroy do

company.decrement!(:users_count)

end

end

2) Migrate to PostgreSQL. It is solved by introducing Lock Type and detects deadlocks automatically and aborts one of the transaction
What I Didn’t Know About the Rails Generate Command
By: Olivier Dumas
Tags: Ruby, Software Development, Ruby on Rails, Programming, Rails

You Can Create Custom Generators

If the default rails generators aren’t enough for you, you can create your own generators. For example, to create new services rails g service or to create new initializers rails g initializer etc.

Rails generate generator

Remember this generator list that we saw at the beginning of the article? Look inside the Rails group and you will see generator .

Yes, Rails has a default generator that allows you to create your own generator!

Generate an initializer generator?

rails generate generator initializer

create lib/generators/initializer

create lib/generators/initializer/initializer_generator.rb

create lib/generators/initializer/USAGE

create lib/generators/initializer/templates

invoke test_unit

create test/lib/generators/initializer_generator_test.rb

Create the lib/generators/initializer folder.

folder. Create the initializer_generator.rb file that inherits from Rails::Generators::NamedBase . As the Rails documentation says, this means that our generator expects at least one argument, which will be the name of the initializer and will be available in our code in the variable name .

The source_root method points to where our generator templates will be placed.

Create a USAGE file, it will actually be your custom generator documentation:

I’ve edited the file just for the example. When I enter rails generate initializer --help in the terminal I now see the following:

Usage:

rails generate initializer NAME [options] Options:

[--skip-namespace], [--no-skip-namespace] # Skip namespace (affects only isolated applications) Runtime options:

-f, [--force] # Overwrite files that already exist

-p, [--pretend], [--no-pretend] # Run but do not make any changes

-q, [--quiet], [--no-quiet] # Suppress status output

-s, [--skip], [--no-skip] # Skip files that already exist Description:

Explain the generator Example:

Hello from the initializer doc This will create:

a/new/initializer

Create the lib/generators/initializer/templates folder. This folder will include the basic template for your custom initializer generator.
Adding UUID column to Rails and Postgresql table
By: Med Bouzid
Tags: Rails, Uuid, Postgresql

Most articles in the internet talks about using UUID as a replacemenet for ID, however sometimes you want to use UUID as an extra column, it depends on the use-case, but doing this is easy!

First we need to generate the following migration:

rails g migration enable_uuid

class EnableUuid < ActiveRecord::Migration[6.0]

def change

enable_extension 'pgcrypto'

end

end

Then you can simply add a new column (UUID type) to your existing table:

rails g migration addCustomColumnToTable

and add your custom column:

add_column :custom_column, :uuid, :uuid

Setting the UUID column can be done either via code:

your_model.customo_column = SecureRandom.uuid

or you can let the database generates it for you by default, in this case you have to consider adding a default value when you create the migration we saw before:

add_column :custom_column, :uuid, :uuid, default: "gen_random_uuid()"

Congrats! mission completed!

**Note: above we used pgcrypto extension, which seems to be the recommended one by postgresql doc, another extension that exists (you may see other people using it) is uuid-ossp in case you want to use it change the extension when generate the first migration to:

enable_extension "uuid-ossp"

then when adding a column, the default should be uuid_generate_v4() instead of gen_random_uuid()

add_column :custom_column, :uuid, :uuid, default: "uuid_generate_v4()"

The difference between the 2 extensions? all I know is that pgcrypto is recommended, but feel free to ask google for more info :)

Best!
Hiding keys and secrets in Ruby on Rails
By: Andrew Mullan
Tags: Rails, Github

When creating a Ruby on Rails backend, you may want to utilize an external API or set up JWT. In the case of an external API you will likely need an API key when making requests to the server. If this key is exposed to the public and someone were to find it, you could end up incurring large fees depending on the external APIs charging system. With JWT your token is encoded with a secret. If your secret lives within your code and it exposed to the public, it’s not much of a secret anymore and could be used to steal your user’s information. Something as simple as uploading your project github can expose these private pieces of information to the public and cause financial losses or headaches in the future. So how do we protect this information, while still making our code visible on github?

The dotenv Gem

There are multiple ways to hide stuff from the public when uploading to github, but the method I will be going over today utilizes the dotenv gem.

To use the gem in your Rails project, add the following to your Gemfile:

gem 'dotenv-rails'

After saving your Gemfile, run bundle install to install the gem and any dependencies.

Now that we have the gem we will want to create a new file in the root directory of our project. In the terminal navigate to the root directory and enter the following to create our .env file:

touch .env

This is the file where all our secrets will be stored. To make this file not upload when pushing to Github, we’ll want to add this new file to our .gitignore. Open up the .gitignore file in the root directory and add the following to a new line.

/.env

Everything is now setup to protect the data in the file from being exposed via Github, but how do we actually use the .env file?

Using the dotenv Gem

We will first want to update our .env file with the keys we want to store. Open the .env file with a text editor and add a line for each hidden value you will need in your project. Keys should be entered in the following format:

EXTERNAL_API_KEY=12345678910ABCDEFG

JWT_SECRET=KEEPITSECRETKEEPITSAFE

After saving the file, you will now have access to these keys in your rails project using the following:

ENV["EXTERNAL_API_KEY"]

ENV["JWT_SECRET"]

These values can be stored to variables or interpolated in strings in your code. Now when pushing your project to Github, you can still show off all of your beautiful code to the public without giving away your secrets!

Note regarding Heroku

If you are planning on hosting your Rails project on Heroku, then the .env file will be ignored when pushing your app. Don’t worry though, you won’t have to change your code for Github and Heroku, you just need to add these keys to your project’s config vars with the same key name you did in your .env file and everything will work. For more information on setting up your app’s config vars on Heroku, please reference their site’s article on the subject.
What I didn’t know about MIME types
By: Olivier Dumas
Tags: Ruby, Software Development, Ruby on Rails, Code, Rails

The basic definition 🤓

MIME types stands for Multipurpose Internet Mail Extensions.

As the doc says, MIME types indicates the nature and format of a document, file, or assortment of bytes.

In other words, they are used by your web browser to know what is the type of the file it has received from the server.

MIME types are everywhere 🌞

When a user navigates across your website, he / she is actually making requests to your server and your server sends back the files needed through the HTTP protocol (images, json, html, javascript etc.).

When the server sends back the files, it also sends a header that includes the Content-type entity that looks like this

Content-Type: text/html; charset=UTF-8

Browsers use the MIME type, not the file extension, to determine how to process a URL. (source: MDN)

Every web browsers have their own list of MIME types that they supports, thus once your browser knows the MIME type sent by the server, it will match this MIME type with its own list of MIME Types and interpret your file accordingly.
A/B Testing With Ruby on Rails
By: Amit Friedmann
Tags: Livewire, A B Testing, Engineering, Rails, Split

Some of the latest features we introduced on the Livewire Market’s platform were firstly running as an experiment for a few weeks. What’s an experiment? When you know your end goal (“Increase the number of users that discover this new page”) and you also have a few ideas on how to achieve it, you can choose to experiment with them simultaneously. Ideas are not enough though — what if by implementing them you’ve been detracting users from doing the same thing you want them to do? Or maybe, you were sure that a button with a blue navy background colour is working the best, while your users are engaging more with a gold one?

The experiment

An experiment allows you, as a product owner, to run multiple variants you want to try in order to achieve your goal. You split the variants between the users on your site, either equally or by some formula (“60% A, 40% B”). It’s what A/B Testing means — test variants (A and B, maybe C and D too) and find the one that works the best.

An experiment for a user has a start — The user is experiencing one of the variants you set them up with. It also has an end — the same user decides to follow the lead and go and check that new page. That is called a Conversion (the user “completes” the experiment).

A winner is born

When you spot a trend of a variant outperforming the others, you can choose to declare it as a winner and force that variant to everyone, concluding the experiment. Be careful not to jump to any conclusions too early in the process. You want to observe the experiment long enough before making a decision.

A/B Testing on Rails

There are a few Ruby libraries which allow experiment development for Rails. We’ve been using split — they allow running multiple experiments all at once, each with multiple variants, and has plenty of configuration options and it “just works” with our Redis configuration.

In this example of our test server, you can see the different variants (or alternatives, as split calls them), how many participants (users) experienced them and how many completed.

Setup

We configured split to support multiple experiments and to persist in a cookie the chosen variant of an experiment for one day. Read more about it here.

Then, we set up the different alternatives in our Yaml file:

If you look carefully, the ‘wire_byline’ is distributed evenly between two alternatives, each with its own metadata, while ‘similar contributors’ having 4 alternatives, 3 that are together shown to roughly 10% of our users (distributed evenly) and for 90% it is not presented at all.
Creating a dummy API using Sinatra.
By: Wamae Benson
Tags: API, Rest Api, Sinatra App, Ruby on Rails, Rails

Install Sinatra gem

gem install sinatra

api_app.rb

require 'sinatra'

require 'json' get '/' do

'Hello world!'

end

request.body.rewind

request_payload = JSON.parse(request.body.read)



if request_payload['username'] == '

{data: {access_token: '2y7348y43tj04fdafdsfds'}, message: nil, success: true}.to_json

else

{data: nil, message: "Unauthorized", success: false}.to_json

end

end post '/sign_in', provides: ['json'] dorequest.body.rewindrequest_payload = JSON.parse(request.body.read)if request_payload['username'] == ' email@d omain.com' && request_payload['password'] == 's3cr3t'{data: {access_token: '2y7348y43tj04fdafdsfds'}, message: nil, success: true}.to_jsonelse{data: nil, message: "Unauthorized", success: false}.to_jsonendend

Starting the app

ruby api_app.rb -o 0.0.0.0

The -o 0.0.0.0 allows you to access the app over the local network. It’s similar to rails s -b 0.0.0.0

What next

Here a challenge. Use SQLite to store data.
Overriding private methods of superclass in Ruby
By: Mehdi Farsi
Tags: Ruby, Oop, Ruby on Rails, Programming, Rails

Photo by Dayne Topkin on Unsplash

Overriding private methods of superclass in Ruby

As Ruby is an OOP language, a class can inherit from another one. In Ruby, the inherited class is commonly referred as superclass — This name comes from the Class#superclass method which returns the direct inherited class of the receiver

Here, Parent class defines the role method. Child class that directly inherits from Parent , can call this method. This is due to the Method Lookup Path mechanism.

Feel free to read the Ruby Object Model article if you’re not familiar with this mechanism

Inheritance and private methods

In Ruby, a private method is a method that can only be called with an implicit receiver — or with self as receiver since Ruby 2.7.

Here, the role private method is accessible in the inheriting Child class. So the state of an inherited method is kept through inheritance.

Now, what happen if we override the role private method?

Overriding a private method

Here, Child class overrides Parent#role private method. In this case we can see that role is defined as public method after this overriding. Also, private_methods does not include #role even though this method is private in the ancestor chain of Child — through Parent#role method.

Indeed, private_methods knows that Child defines a role method. and as Child is the first entry of the ancestor chain (and the message handler during Method Lookup Path for a call to Child#role ), it’ll be considered as the right version of #role to check by *_methods routines. So as Child#role isn’t defined as private, the private state of Parent#role isn’t inherited by Child#role .

Conclusion

So, always be careful when overriding methods defined with a specific access control. Indeed, this state won’t be shared amongst the different versions of your method.

Voilà!
Переход от бессерверного проекта к Ruby on Rails
By: Samoilenko Yuri
Tags: Serverless, Railsagain, Ruby, Ruby on Rails, Rails

Learn more. Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Make Medium yours. Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore
What Exactly Does the Serializer Do?
By: Jonelle Noelani Yacapin
Tags: Active Model Serializer, Javascript Tips, JavaScript, Rails, Serializers

Cereal Guy

After dabbling in Ruby on Rails and venturing into JavaScript, I found it very useful to have Rails as the backend API. It is setup in such a way where it can easily render JSON data to be used on the JavaScript side and therefore the browser.

Building my app was going well until it came time to render attributes of a model in relation to another model.

In Ruby, the relationships are set up like so and through naming conventions it knows where to look for whatever it’s looking for. Here, I have 3 models in a many-to-many relationship.

class Review < ApplicationRecord belongs_to :user belongs_to :wine end class User < ApplicationRecord has_many :reviews has_many :wines, through: :reviews end class Wine < ApplicationRecord has_many :reviews, :dependent => :destroy has_many :users, through: :reviews end

In a Rails app, to create the frontend I would just need to create html.erb files within a folder (within app/views folder) that correlates with the above models by sharing the same name (naming convention). Then, in the controller actions I would just need to specify what to render. Through naming convention of the files, Rails automatically (almost magically) knows what is linked to what and therefore what to render.

But, I’m venturing into using JavaScript/HTML as my frontend, remember?

So, in the controller actions I need to tell the app what to render (via ‘render json:’ then whatever specified to render).

For example, the show action in app/controllers/users_controller.rb:

class UsersController < ApplicationController def show render json: User.find(params[:id]) end end

After a couple attempts I realized that the relationships I established in rails were not coming through on the frontend. For awhile I thought my JavaScript was wrong. No, I need a serializer.
Use a Ruby Linter
By: Damien Burke
Tags: Rails, Rubocop, Linter

Use a Ruby Linter

Published: November 17, 2020

This is part of The Annotated Guide to a New Rails App, a list of recommendations to make developing your Rails app more productive and joyful.

In this article, we are talking about using a Ruby linter.

When

The longer you wait to add a Ruby linter, the more work you will have to correct style errors that have accumulated. For that reason, I recommend adding a linter, such as RuboCop, as early as possible.

Why

Having a consistent style makes code easier to read and maintain. Using a linter makes it easy to conform to a consistent style. In a lot of cases, your linter can make corrections automatically.

How
The Flatiron Rails Tutor App
By: Dmitriy Malayev
Tags: Software Development, Tutoring, Project Management, Flatiron School, Rails

Hello, my name is Dmitriy Malayev, and I am a current student at Flatiron School. For my third project assignment (also known as Mod 3) I have decided to implement a rails app with a Tutoring functionality.

My project consists of four major models; Appointment, Student, Tutor, and User. As well as five controllers, omniauth_callbacks_controller, application_controller, appointments_controller, students_controller, and a tutors_controller.

All of my models have incorporated validates, which is used for normal validates in addition to validate which is used for custom validations making sure requested information such as a student’s name if requested must be present.

My Join Model is Appointments, which belongs_to :tutor and :student.

My User Model has_many :students, has-many :tutors, through: :students, and has_many :appointments, through: :students

My Student Model belongs_to a :user and a Student also has_many :appointments as well as has_many :tutors, through: :appointments

My Tutor Model has_many :appointments and has_many :students through: :appointments

Regarding the 5 Controllers, most of them have incorporated two major methods which are before_action :authenticate_user! and before_action :set_(name of variable).

The first one (:authenticate_user!) made sure a User is both logged in and authenticated before any method can run, assuring that a User can’t do anything until they do so.

The second one (:set_(name of variable)) implemented a method from a popular Devise Gem which is current_user.

The way I have implemented this for a student model (as an example) is like this:

def set_student

@student = current_user.students.find(params[:id])

end

This would access the current user’s students and call the find method using params[:id] if it’s nil the unauthorized User will be sent to the home route which will prevent anyone from viewing, editing, updating or deleting something they have not created. If it’s not nil, it will be assigned to the instance variable.

In my project i have implemented many gems, out of those I will mention 3.

gem “devise”

This gem is one of the most popular rails gems, because it provides many benefits such as the current_user method mentioned above. It’s main function is authentication, but it also is useful for, incorporating password reset functions, setting up email, and much more.

gem ‘omniauth’

This is a library that standardized multi-provider authentication for web applicaitons. It was created to be a powerful, flexible and do as little as possible.

gem ‘omniauth-google-oauth2’

This is the same as above but specifically made for Google Authentication.

Also, I have incorporated a calendar system for booking an appointment, made sure there are no conflicts such as double bookings, and incorporated gifs and a great transparent background.

Thanks for reading.
We Can’t Neglect Basic Infrastructure Assets
By: Timothy Little
Tags: Transportation, State And Local, Transit, Rails, Infrastructure

Often when thinking about infrastructure investment images of new bridges, train halls, or massive highway interchanges are envisioned. But an often-overlooked aspect for many are basic infrastructure assets or the kinds of things that keeps the lights on and in a state-of-good-repair.

State-of-good-repair is where a backlog of projects are concentrated for governments across the country. These needed investments are significant and likely exceed over a trillion dollars, but there is no easy way to quantify the cost.

The State of California has taken on the task of estimating its deferred maintenance. In the state’s 2019–2020 budget, the administration identified “a total state infrastructure deferred maintenance need of about $70 billion.” Of this amount, about $50 billion was related to the state’s transportation system.

It’s not surprising that the backlog mostly relates to transportation, since that is where the bulk of most public assets are located. The BEA estimates nearly a third of all state and local government fixed assets are streets and highways. And according to the American Society of Civil Engineers (ASCE) in 2017, U.S. underfunding of its highway system resulted in an “$836 billion backlog of highway and bridge capital needs.”

By failing to keep-up with deferred maintenance, projects typically end up costing more to fix with each year of delay.
Google Adwords with rails(part 1)
By: Huang Yu Ti
Tags: Rails, Adwords, Google Adwords, Google Api

Start Code

I used the https://github.com/googleads/google-ads-ruby.

Get Client All Adword Account ID And Account’s Inform

The refresh_token is accessed by client and

client.service.customer.list_accessible_customers().resource_names

response client’s all adwords’ account id. It looks like customers/XXX-XXX-XXX

The step can success by test developer_token. And

resource_name = client.path.customer(ad_words.gsub("customers/", ""))

customer = client.service.customer.get_customer(resource_name: resource_name)

response account’s inform. client.path.customer({ customer's id}) . It inputs only the number.

The step needs basic developer_token( be reviewed ), or it will response auth error.

Finally, We finished Adword Api start. Next time we will get campagin’ s cost amd search by time.

reference:
Two Reasons to Use Scopes instead of Class Methods in Rails
Tags: Chainable, Classe Methods, Lazy Loading, Rails, Scopes

In one of my previous blogs, I explained the difference between Scopes and Class Methods in Rails. In this blog, I will explain two benefits of using Scopes instead of writing them as regular Class Methods.

What happens when you define a scope in Rails

Scopes are just methods that get converted internally by Active Record to Class Methods. For instance, a simplified implementation of ‘A’ student scope would look similar to this after it gets converted to a class method:

def self.a_student

where(grade: 'A')

end

That's why many developers don’t feel the need to write scopes instead of class methods believing that it is just another way or a syntactic sugar to write a class method. However, here are some benefits that you only get if you are using Scopes:

Scopes are chainable

Unlike regular methods, Scopes can be chained to one another. Let’s explain this with an example. Assume you have the following two scopes:

class Student < ActiveRecord::Base

scope :female, -> { where(gender: 'female') }

scope :a_students, -> { where(grade: 'A') }

end

Here, I have two Scopes, female and a_students. One will return all female students and the other will return all ‘A’ students. By having that, I can chain both scopes to get all ‘A’ students that are females.

Student.female.a_students

The nice thing about this is that only one SQL query will be executed. For our female ‘A’ students, Rails will generate only the following SQL query:
ActiveRecord N+ 1 問題和解法
By: 袁浩 Harry Yuan
Tags: Rails, Activerecord, N Plus 1 Problem

ActiveRecord，一直是Rails工程師的好夥伴。

透過他的ORM性質，我們可以直接用Ruby的程式語言去DB拿資料，省去了很多直接寫SQL的麻煩。

@articles = Article.where(created_at: (Time.now - 1.day)..Time.now)

好用歸好用，但當我們沒有小心使用他的話會造成很多不必要的效能問題，也就是所謂的「N+1問題」。

這個問題因為很常發生，所以你隨便找都找得到相關文章，但也許你可以從我這邊得到一些不一樣的收穫。

TL;DR

N+1問題一句話來形容就是：

「做一兩次就可以完成的事情，卻多做了很多次」

「訂了外送飲料跟吸管，外送員本來跑一趟就可以送來所有東西，但是他只送了飲料來，才跑回去拿吸管來，跑了兩趟。」

只要解決這個問題，不僅API效能大增，更是大大減輕了DB的負擔。

真實情況呢？ActiveRecord中何時會發生？

假設我們的app有文章系列的功能，模型的關聯如下：

但今天我們想要在文章列表（ articles#index ）中存取他的 comments ，比如說我們要看每篇文章的最新留言：

看log你會發現，View裡每一次的迴圈都會去 Select comments：

FROM articles

SELECT * FROM comments WHERE comments.article_id = 1 order by id desc limit 1

SELECT * FROM comments WHERE comments.article_id = 2 order by id desc limit 1

SELECT * FROM comments WHERE comments.article_id = 3 order by id desc limit 1

SELECT * FROM comments WHERE comments.article_id = 4 order by id desc limit 1

SELECT * FROM comments WHERE comments.article_id = 5 order by id desc limit 1

SELECT * FROM comments WHERE comments.article_id = 6 order by id desc limit 1

SELECT * FROM comments WHERE comments.article_id = 7 order by id desc limit 1

SELECT * FROM comments WHERE comments.article_id = 50 order by id desc limit 1

...

我們可不希望人家看一次文章列表，資料庫就被玩壞了。這個故事的教訓就是：「一開始就要把東西準備好！不要分那麼多次拿東西」
Rails 6 setup on macOS Big Sur. macOS Big Sur is out now. My previous…
By: Alan Reid
Tags: Macos Big Sur, Developer, Rails 6, Rails, Development

macOS Big Sur is out now. My previous setup tutorials seemed to help a few people setting up their Rails environment, I decided to write this updated version to help you setup your Rails enviroment on macOS Big Sur.

You will need to use the mac’s build in terminal, or you could download and install my favourite - iTerm 2. But thats down to your personal choice.

Install NodeJS

Before we start you will need to make sure you have installed NodeJS. If you visit the NodeJS site at https://nodejs.org/ and download and install the LTS package. Once you have done this we can move on.
Monetize your Side Hustle with Stripe’s API for Rails
By: Brittani Élan Taylor
Tags: Rails, Stripe, Ruby

A guide to upgrading your digital lemonade stand

Maybe you think Etsy’s overrated? Or you just have quite the independent streak? Either way, if you’re reading this, you’re ready to take on the challenge of handling payments in your Rails API.

Luckily, Stripe makes it easy with this customizable API that saves you the trouble of storing user payment information on your website (which would leave you vulnerable to cyber attacks on even the best days).

Project setup

Install the Stripe Ruby gem. After adding the following to your Gemfile, run ‘bundle’ in your terminal.

Server code

2. On the server side (aka your project’s backend), add an endpoint on your server that creates a one-time checkout session for whatever product(s) you have in mind. A Checkout Session controls what your customer sees in the Stripe-hosted payment page.

There are various areas for customization in the above code:

Stripe recognizes 7 different payment methods. Learn more about them here

Within the line_items object, you can define product information when you create the Checkout Session with price_data or alternatively use pre-defined prices and pass their IDs.

or alternatively use pre-defined prices and pass their IDs. Checkout has three modes: payment , subscription , or setup . Payment is for one-time purchases, and what we’re demonstrating here.

Client code

Note that in the code above, one’s able to specify URLs for success and cancel pages, but this can also be handled within the same URL (examples below from Stripe for multiple URLs)

TLDR: Adds a success page — Creates a success page for the URL you provided as the Checkout Session success_url to display order confirmation messaging or order details to your customer.

TLDR: Adds a canceled page — Adds another page for cancel_url . Stripe redirects to this page when the customer clicks the back button in Checkout.

TLDR: Adds an order preview page — Allows the customer to review or modify their order — once a customer is sent to the Checkout page, the order is final.

Almost there!!!

Now, all that’s left is to start your server with ‘rails s’ in your terminal, and then and navigate to http://localhost:3000/checkout.html (or whatever your BASE_URL is)

And the testing begins. Stripe provides a number of card and account numbers to test depending on the payment method designated above. You can find them here. The most basic ones you can find below.

Payment succeeds — 4242 4242 4242 4242

— 4242 4242 4242 4242 Payment requires authentication — 4000 0025 0000 3155

— 4000 0025 0000 3155 Payment is declined — 4000 0000 0000 9995

Demo below to see the final product

Find a link to a demo here!!
I like the examples about how concerns can turn bad
By: Josua Schmid
Tags: Rails, Mixin

While I am greatly thankful for your examples about how concerns can turn bad, I want to show you this

https://twitter.com/dhh/status/964244090224128001

In contrast to many of your readers, I think this image shows a very good example on how to not have bidirectional dependencies while using concerns. The model doesn't rely on any feature included by a concern. I guess the concerns are well engineered, depend on framework features and not on each other (except for the ones mentioning it in the comments).
Switch to UUIDs
By: Damien Burke
Tags: Rails, Uuid, Postgresql

Switch to UUIDs

Published: November 10, 2020

This is part of The Annotated Guide to a New Rails App, a list of recommendations to make developing your Rails app more productive and joyful.

In this article, we are talking about switching the database primary keys to UUIDs, universally unique identifiers.

When

On one hand, it is not trivial to change a table’s primary key from the default integer to UUIDs. For that reason, it is helpful to switch to UUIDs as early as possible.

On the other hand, the benefits of using UUIDs are generally not an important concern for new applications, so there is little reason to do it right away.

Why

By default, Rails uses integers as primary keys. Using UUIDs instead prevents ids or the number of entries from being guessed. Using UUIDs also avoids an integer overflow problem if many objects are created.

How

Enable UUIDs in PostgreSQL:

We assume you have already made the switch to PostgreSQL.

Generate a migration: rails generate migration EnableUuids . Put this in the change method of the migration: enable_extension 'pgcrypto' Run the migration: rake db:migrate

Configure the generators to use UUIDs as primary keys:

In config/application.rb add config.generator.orm :active_record, primary_key_type: :uuid .

Test the change

After making a commit, test that this works by running rails generate model foo and rake db:migrate .

The migration and schema should both indicate that the id is a UUID.

Run rake db:rollback and remove the generated files before continuing.

Gotchas

When creating a foreign key column (using references or belongs_to ) you must indicate the type if the id is a UUID.

For example:

create_table :post, id: :uuid do |t|

end



create_table :comment, id: :uuid do |t|

t.belongs_to :post, type: :uuid

end

If you do not do this, there is a risk of silent errors when the UUIDs are coerced into an integer to fit into a column that expects an integer.
Associations between classes
By: Bryan Gonzalez
Tags: Rails, Coding, Association, Has Many Through

Association rails, associations in rails is sometimes a hard concept to wrap peoples head around but I’ll try to simplify.

Let us imagine we are building a pizza delivery application where our user class carries the users name and address and where pizza has different variation of pizzas. We create our models by running

rails g model pizza pizza:

rails g model user name: address:

Then the next step is to make a single source of truth.

Currently our models have no relation. However now when we create our joiner class, which will be Order class. Our order has to know our pizzas and users, so we generate a model

rails g model Order user:references pizza:references

when we create our attributes with references, rails does a bit of its magic and allows us to access information from different classes now let’s say we wanted to create a list of all the user is associated with we will be able to access @instance_variable.pizzas. we would be able to because we have not created our relationships.

So now we create the relation between the single source of truth and the the other class. which involves us having to go into the models and explicitly state the relation between models.

class Pizza

has_many :orders

has_many :users, through: :orders

end

class Order

belongs_to :pizza

belongs_to :user

end

class User

has_many :orders

has_many :pizzas, through: :orders

end

Make sure that when you create the relations that the other models are associated plural and now users will be able to get information that isn't from the user original class.
Quick Guide on Validations in Rails
By: Karina Guerra
Tags: Rails, Validation, Ruby, Learning To Code

Here we have a list of randomly pre-created basketball players and a form to create new basketball players. This new players will be added to the list on the index page. As you can see, the player class have four attributes: name, age, player number, and their position.

Here are the validations we want to add:

A player’s age must be over 18.

A player’s number must be between 1 and 99.

A player’s name must be present.

Step 1: Adding the Validations

Like we mentioned before we are using Model-level validations. So we must add these validations to our model file.

Model File with Validations

Here I have used the validates method. This method takes two arguments:

The attribute to validate

A hash of options that details how we should validate this attribute

To validate a players name I validated the attribute :name and I used the presence validation helper to ensure that a name is typed into the text field of the form. For the :number attribute, I used the numericality validation helper to ensure that a numeric value is given and that it is both greater than 0 and less than 100. And similarly to the previous validation, I used the same validation helper to ensure that the player is 19 years old and above.

Step 2: Implementing the Validation

Now that we have defined our validation. We need to implement it! For next step we move to our controller.

PlayerController

When a user tries to create a new player and submits a form, the create method will be called upon. The create method is the point where data will be added to the database. It is at this point where we want to validate our data before it is persisted to the database. First we create a new instance. Then we use the #valid? method to check the datas validity. This is will refer back to validations we defined in the model file. If it passes, the instance will be save, thus added to the database. If it is not, an error(s) will be added to the object which we can temporarily hold in flash hash . After adding that error or those errors, the user is redirected to the form so that they can try again.

Step 3: Displaying Errors

After implementing, we need to be able to display these errors to the user if any do occur. We do so by adding it to our form which would be located on our new page.

New page

As you can see, before we display our form to create a new player, we will display any errors we may find if they are present. We can display each error that is held with the flash hash . If none are present, no error will pop up instead the form will display like normal. However if the user has already tried to submit a form that contained invalid data, they will see errors in a big red text.

Here is an example of invalid data being submitted:

Invalid data being submitted

However if we write in valid data: