fabiochiu/medium-articles huggingface dataset:
Introducing iterable_rails
By: Lewis Buckley
Tags: Ruby on Rails, Rubygems, Email Marketing, Transactional Emails

Introducing iterable_rails. A Ruby gem for sending emails via Iterable with Rails.

Earlier this year we released Iterable Rails, a Ruby gem that makes sending emails from Ruby on Rails via Iterable, super simple.

Background

As a team we decided it would be useful to consolidate our use of a variety of email services into a single email service provider. We originally used Mandrill for transactional emails, Mailchimp for our newsletter, and Blueshift for our other marketing emails.

After considering all of our needs across the whole business, both as a product and engineering team and a marketing team we settled on Iterable.

Iterable supports no-code functionality that would allow our marketing team to autonomously develop and send marketing emails. These could be based on existing events that we already sent from our Ruby on Rails application to Segment. An example of this is our “Welcome series”, a series of emails that we send to users after they sign up for BiggerPockets.

It also had a pathway to support our transactional email needs but we couldn’t find a Rails-native way to make use of this.

Migration

The first step in moving to Iterable was migrating customer data and templates from our previous email service providers into Iterable. We have open sourced the (hacky!) scripts used in this migration and those are now available on GitHub! After migrating data from Mailchimp, Blueshift and Mandrill into Iterable we were ready to begin sending transactional emails from within Ruby on Rails.

Goals

Our primary goal was to make sending email via Iterable as easy as possible for us as Rails developers. Secondary was the ability to isolate our application code from our email provider. For example this gives us the ability to use another service provider as a backup, should Iterable have any issues.

Fortunately, ActionMailer supports our use cases and makes adding custom delivery methods (and switching between them) very straightforward.

Our solution was Iterable Rails.

Usage

It’s necessary to create a triggered email “campaign” within Iterable, and create an email template within that campaign. Setting the template body to a single handlebars tag such as “html” means that we can then render the HTML within Ruby on Rails and send it to Iterable via their API:

{{{ html }}}

Iterable campaign setup

Conclusion

With these steps completed it’s simple and straightforward to send emails via Iterable from within our Ruby on Rails application. For more information please check out the Iterable Rails readme.

If this sort of project sounds interesting to you, we’re currently hiring! Visit BiggerPockets Career Opportunities to find out more.
How Rails Generators Make CRUD Workflow Go Smoother
By: Noura Loudani
Tags: Ruby on Rails, Beginner, Generator, Rails

Photo by Michael Hodgson, New York 2019

Ruby on Rails or Rails is a user-friendly open source framework. Its main goal is to optimize the web application development process.

Rails developers must follow standard best practice conventions in order for the magic to happen. Rails is built on the principle of convention over configuration (for example: a model is singular — a controller is plural).

Generators are a nifty way of integrating standard features that help creating CRUD functionalities in an application. So instead of having to build them manually each time, Rails came out with a faster automated way. Let’s break this more down by running rails g in the command line of a rails application:

General options:

-h, [--help] # Print generator's options and usage

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

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

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

-q, [--quiet] # Suppress status output Please choose a generator below. Rails:

application_record

assets

channel

controller

generator

helper

integration_test

jbuilder

job

mailbox

mailer

migration

model

resource

scaffold

scaffold_controller

system_test

task ActiveRecord:

active_record:application_record TestUnit:

test_unit:channel

test_unit:generator

test_unit:mailbox

test_unit:plugin

We see a list of all built-in generator, from application record to task . If we want to generate any of them, all we need is run rails g (name of generator we want to generate).

Let’s compare two of the most common commands. rails g resource vs rails g migration . I personally consider the first one to be the smartest of all. For example, running rails g resource SignUp username id_number:integer would mainly create the following:

A migration file with the proper name/path: /db/migrate/20201221141414_create_sign_ups.rb, as well as the corresponding attributes:

class CreateSignUps < ActiveRecord::Migration[6.0] def change create_table :sign_ups do |t| t.string :username t.integer :id_number t.timestamps end end end

A model file that inherits from ApplicationRecord

class SignUp < ApplicationRecord end

A controller file that inherits from ApplicationController

A view directory

A full resources call in the routes.rb file

On the other hand, for example, we can add a new table to a data base by running rails g migration <SignUp> . This create the migration file ‘’######_sign_up.rb

class SignUp < ActiveRecord::Migration[6.0] def change end end

Our take on this: Rails generators follow Rails best practices, which includes utilizing RESTful naming patterns.
Using a Web API in Rails
By: Dana Jackson
Tags: Beginner, Webapi, Ruby on Rails, Ruby, API

In this blog post you’ll learn what is an API and how it can be applied in a Ruby on Rails application.

What is an API?

You’ve probably heard the term API thrown around by developers and novices alike, maybe with descriptors like private API, public API, or partner API. How about local API, program API, or web API? It’s difficult to define APIs as a whole because there are many types that serve many purposes. At its core, an API (Application Programming Interface) is code that allows two entities to exchange information. It is an interface (the I!), or a middleman, that controls the passage of data.

When using a web API, the requested data is being passed from the server, via the API, to the client (you and your web browser). It is usually returned in JSON (JavaScript Object Notation), a language-agnostic format that likely includes nested data structures.

It’s useful to understand the request-response life cycle as you begin working with APIs:
How to Utilize Image Upload with your Heroku Application
By: Ellen Park
Tags: Ruby on Rails, Ruby, Software Engineering, Heroku

Implement Heroku’s new add-on feature Simple File Upload

Photo by Caleb Carl on Unsplash

For one of my recent Rails projects I created an application that allowed users to create accounts, add pets to their accounts, and connect with other pet owners. I included a feature that allowed users to upload files for pet profile images. It seemed simple enough until I tried to deploy my app to Heroku. I immediately ran into an issue with Heroku’s ephemeral file system. As stated by Heroku:

Each dyno gets its own ephemeral filesystem, with a fresh copy of the most recently deployed code… …For example, this occurs any time a dyno is replaced due to application deployment and approximately once a day as part of normal dyno management.

Bad news for me. But lo and behold, Heroku recently released a new add-on called Simple File Upload. With this add-on you can upload files directly to cloud storage just with Heroku! Before we start implementing Simple File Upload to an existing Rails application, make sure you’ve completed the following prerequisites.

Update billing info for your Heroku account (Must have valid credit card on file). Your Rails application must already be deployed on Heroku (if it’s your first time deploying to Heroku, here is a great tutorial).

With those two steps out of the way, let’s get started!
Top 10 In-Demand Web Development Frameworks in 2021
By: Md Kamaruzzaman
Tags: Web, Laravel, Vuejs, Ruby on Rails, React

There are many Web development frameworks in the market. Choosing the right framework is a complex and tricky task. If you are an enterprise, choose a framework that will be maintained for the next 5 years and fit your company's resources and goals. If you are a developer looking for a job, choose a high demand framework in the job market, and fit your profile.

Here in this article, I will list 10 such frameworks for both enterprises and developers. Here are my criteria to choose the web development framework:

Mainstream and well adapted in the industry.

Highly popular with stable or increasing popularity.

They are in-demand in the job market.

They are not a legacy framework (e.g., jQuery) or not in maintenance mode (e.g., ASP.NET, AngularJS).

To find the frameworks' popularity, I have used data from reliable sources (GitHub, StackOverflow Developer Survey). To find the Job market demand, I have used the Job Search engine Indeed's data (for the USA only).

1. React

In recent years, JavaScript-based client-side web frameworks are dominating web development. While React is not the first one, it is the most popular and disruptive among them. Facebook has developed React as a simple JavaScript library to implement the Web's view layer in a component-based way and released in 2013. It also differed from the existing JavaScript framework as it advocated the one-way data binding. Within a short time, React became overwhelmingly popular among Enterprises and developers. Today, it is the leading Client-side web framework.

Key Features:

React core is just an unopinionated library that implements the View layer for UI. In application development, it is used with other libraries from React Ecosystem for end-to-end application development.

It has the slogan “ Learn Once, Write Anywhere ” as software engineers can use React to develop Apps for any kind of User Interface, e.g., Web, Mobile, Desktop, or even for Smart TV .

” as software engineers can use React to develop Apps for any kind of User Interface, e.g., . Among all the Client-Side Web Frameworks, React offers the best Server Side Rendering with superb SEO support.

support. Facebook is actively developing React and putting their weight behind it. As a result, React features are tested with 2.7 billion Facebook users . It is battle-hardened and will remain in the industry as long as Facebook is there.

. It is battle-hardened and will remain in the industry as long as Facebook is there. It is one of the most disruptive and innovative frameworks. It has popularized one-way data binding, declarative programming, immutable state. It is now working to offer better concurrency support, improved performance, and cleaner code.

Popularity:

React is the most popular web framework, which is evident from different sources. According to GitHub, it is the second most starred Web Framework:

The StackOverflow developer survey 2020 has ranked React as the second most used Web Framework just behind jQuery:
【紀錄】轉職軟體工程師，我的 why what how 與感謝
Tags: 五倍紅寶石, Astro Camp, 轉職, Ruby on 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
An introduction to Hotwire, ActionText and Rails 6
By: Shashike J
Tags: Rails, Web Development, Ruby on Rails, Programming, Ruby

Generate the Application

I generated a new application imaginatively named test_hotwire :

rails new test_hotwire -d postgresql

Next, I ran the ActionText generator to create the necessary boilerplate:

rails action_text:install

After adding the hotwire-rails gem to the Gemfile , I ran the generator for Hotwire:

rails hotwire:install

This generator did a lot of things, including setting up Redis (so make sure you have a redis-server running on port 6379) and ActionCable .

To speed things up, I generated a scaffold for Tweets that generated HTML templates, as well as a model and a controller:

rails g scaffold Tweet

To make any domain model streamable, you simply have to broadcast to a namespace and reference that in your views. For the Tweet model, Rails needs to broadcast to the WebSocket when the following events happen:

Tweet creation Tweet update Tweet delete

ActiveRecord hooks are perfect for this kind of thing, so I dropped in the following code in the Tweet model:

app/models/tweet.rb

Now each time any of those events fire, Rails will broadcast to a public namespace called “tweets” .

The subscriber for these broadcasted events are set up by Turbo . To create a stream, you simply wrap whatever you need in a Turbo frame. So for the tweets stream, I did the following:

app/views/tweets/index.html.erb

On line 13, turbo_stream_from will establish a WebSocket connection to the tweets stream. The turbo_frame_tag will wrap the list of tweets and patch the DOM whenever an event is broadcasted from the back end.

In the partial app/views/tweets/_tweet.html.erb , I wrapped each tweet in a turbo_frame_tag that references its ID so edits and deletes can reference the target tweet on the DOM.

app/views/tweets/_tweet.html.erb

That’s it! In a real-life application, you would probably set up namespaces for each of the streams in your application and prefix them in some way for access control. But this tiny example goes to show how powerful Rails and its first-party libraries have become over the years.

Happy coding!
How to Deploy a Jekyll Project to a Server?
Tags: China, Static Site Generator, Ruby on Rails, Ruby, Jekyll

From Jekyll Official Website

What is Jekyll?

Jekyll is a static site generator written in Ruby. It was one of the first batch of static site generators. It has a wealth of third-party plug-ins making it loved by Ruby developers.

21YunBox provides a very simple Jekyll deployment method. You can quickly and easily deploy with 21YunBox in a static site environment.

How to Deploy Jekyll in China?

Register as a 21YunBox member Fork Jekyll Example on Gitee Create a cloud service on 21YunBox, and allow 21YunBox to access your code base Create with the following configuration:

Why Choose 21YunBox?

21YunBox is a Cloud Service platform based out of Beijing. Our services enable your team to be more effective in leveraging the growing opportunity within China by hosting your sites at blazing speeds with an operational and maintenance free, and low code solution. 21YunBox provides an easy and budget friendly, end-to-end web platform deployment service for all applications from small teams to large enterprises. We also offer full support in obtaining your ICP license allowing you to legally host online content inside of Mainland China.

To learn about the differences between 21YunBox and these foreign (outside of China) cloud service platforms? You can refer to:
Using the OmniAuth gem
By: Felipe Cruz
Tags: Ruby On Rails Development, Oauth, Rubygems, Ruby on Rails, Ruby

Breaking down OmniAuth, and how to use it in your Rails application.

OAuth

OAuth is an open standard for access delegation, commonly used as a way for Internet users to grant websites or applications access to their information on other websites but without giving them the passwords.

That’s a very fancy way of describing a process we’re all very familiar with when using the internet. Examples of this include using your Facebook or Gmail account in order to login to a website you may not have visited before i.e. Medium, without the tedious process of creating an account.

The flow looks something like this:

Application is registered with intended provider(i.e. Google, Facebook, GitHub, etc) and a client_id and client_secret are obtained Application sends out a request to the provider (i.e. Google, Facebook, GitHub, etc) including the application’s client_id and client_secret Provider asks the user if they’d like to authorize the application to access their personal info If yes, the provider sends back a token/code to ‘/auth/:provider/callback’, a route found in the application The application sends out a 2nd request to the provider with the token/code The provider sends a response back with a user’s information The application parses the response to create a hash of user info

So how do we implement this in our Rails app? and how do we use the Omniauth gem? In this example, I’ve used a blogging/history (I like to combine my interests, lol) application. It has all the familiar classes of user, post, comments, and so on.

Let’s get into it.

Setting up the OmniAuth gem:

First, register your application with your intended provider (Facebook, GitHub, Google, etc.) and obtain your client_id and client_secret. You’ll also need to include the relevant gem in your Gemfile and run bundle. In this case, Facebook.

gem 'omniauth-facebook'

Then, go to config/initializers/omniauth.rb, and include the following code along with your client ID & secret.

Rails.application.config.middleware.use OmniAuth::Builder do provider :facebook, 'PROVIDER_ID', 'PROVIDER_SECRET' end

In routes.rb:

get '/auth/facebook/callback', to: 'sessions#create'

Your link will look something like this:

<li class="nav-item active"> <a class="nav-link"> <%= link_to "Sign in via Facebook", "auth/facebook", class:"nav-link active"%> </a> </li>

Now that we have an ability to make a request. Let’s see what Facebook sends back to us. In order to do this, set up your create method in your sessions controller and include a byebug similar to the below:

With this byebug, we can call on this hash in order to see what it contains:

Although I’ve redacted a bunch of information from the screenshot above, you can see that Facebook will provide you with a bunch of useful information regarding the user, even a picture should you choose to display one for each user in your application.

You should now be able to have users log in to your application using their Facebook, Gmail or Github account, among others. Exciting!
The Gem Files: ‘phonelib’
By: Kevin Gleeson
Tags: Formatting, Backend, Phone Number, Rubygems, Ruby on Rails

Step 1: Install the gem

This step is pretty easy, simply add this line of code to your .gemfile and bundle install

gem 'phonelib'

Double check your .gemlock file to make sure that it has made its way into your projects.

Step 2: Make a default country code

If your project is based in a certain country or you would like your country codes to default to a certain country, you can easily do this with the ‘phonelib’ gem.

To start, head to your config/initalizers folder and create one called phonelib.rb

Next, enter this line of code into your new file.

Phonelib.default_country = "US"

Note: If your default country is not the United States, you can check out a list of 2 letter country codes here.

Step 3: Phonelib Validations

Assuming that your phone number attribute is called phone_number your class containing might look like this while implementing the ‘phonelib’ gem.

Use this image for Step 4, too!

Let’s dissect this first starting with our validation, and the go into what our format_phone method is doing.

On line 3, our validations start by initializing the phonelib gem using

phone: { attributes_you_are_validating }

Inside of our phone object, we’re using keywords given to us by the ‘phonelib’ gem. In this case, possible: true, is referring to if the information given to the :phone_number attribute could be a phone number. This checks for things like letters and the length of the phone number. The other validation, allow_blank: false, tells our database to not allow a user to enter an empty form for the phone_number attribute. For a full list of possible validations, scroll back up to the introduction of the gem and check out the docs!

The final validation uniqueness: false, is allowing a user to have multiple devices with the same number. If uniqueness was set to true, phone numbers could not be duplicates in our database.

Step 4: Formatting Phone Numbers

Let’s move onto our class method for a device called format_phone.

If you take a look at line 4 in our example, you’ll see how we’re implementing the ‘phonelib’ gem to format our phone numbers. When we use before_save, it’s going to correspond to a .save method in our controller and will trigger before that save happens. This way, a user can type whatever they want, but before it goes to our database, it will get formatted in the way we’ve told it to.

In our format_phone method, we’re calling the phonelib gem itself, telling it to parse what our user inputed as phone_number at to change it into an e164 format. If you’re new to the formatting phone numbers, check out what e164 means here. Once it’s changed into the format we like, it will save to our database.
Flowing through MVC
By: Jesus Garcia
Tags: Rails, Mvc Frameworks, Ruby on Rails, Routes Guide, Mvc

At first the MVC might seem somewhat confusing and intimidating. I’ll try to explain in simplest terms on what the MVC does. First, what does MVC stand for? Models, Views, and Controller. By connecting the model, controller and views, they can work together in order to help us create a Web App. The model consists of classes that can perform CRUD functions. The Controller takes in a request, evaluates, and gives back a response. The View shows a visual presentation of information and logic in the web browser. Let’s take a quick look of how the MVC flows.

Web Browser and URL Request — Inside the web browser, we type in a URL and will take us to the site. What we are typing is actually a request and the server receiving it will interpret it.

Server Router and Router File — When the server receives it. It will look inside of the route file of the web application. Inside of this file, there will be specified information called routes. Each route consists of a few columns, the first one being the HTTP verb. The HTTP will instruct on whether the request wants to retrieve or give data from our app. The second will be the URL path request. That is the URL we would type to go to that specific page. The third column will consist of the controller and action within that controller. It will look for the controller named before the “#” and afterward the action. After the request gets matched to a route, we will proceed to the controller. (Also, using resources, will help shorten your routes.

Controller — The controller contains all the actions that we want to access. It receives a request and then gives back a response based on the action performed.

Actions — The action contains the logic to be performed when receiving a request. The action connects to our view files. If the name of the action and file are the same, Rails will pair them up naturally. Otherwise, you will need to “render” the file inside the action.

Models and Database — The Model is responsible for CRUD (create, read, update and delete) actions by connecting to the database. Once the model delivers or retrieves data from the database, it will go back to the action.

Views — After the model connects information to the action, the action will proceed to the view file. The view will be a representation of what we want the user to see in the web browser. Inside the view file is where all the html code will be contained. After it compiles the code, wit will send back a response.

Response to the Web Browser — The response is what we see when the MVC has finished working together and done its job. It will display all the information asked for on your web browser.

I hope this helped to understand the way that the MVC structure works. It really shows that it was created with detail and logic. MVC really helps with the organization, structure and refactoring of code we type.
Rails設定權限套件-pundit
Tags: 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
Dabbling with ViewComponent
Tags: Viewcomponents, Refactoring, Design Patterns, Ruby on Rails, Ruby

In an effort to reduce the amount of JavaScript in our application, our team has been writing more server-rendered views. Like most things in software engineering, there comes a point when things don’t quite scale.

Our partials became long, complicated, and hard to test, so we figured there had to be a better way. And that’s when we discovered that GitHub had run into the same issue and had created a gem exactly for this purpose: view_component!

View Component allows you to create components in Ruby that leverage the presenter pattern and thus sit between the controller and the view. This allows for more testability, reusability, encapsulation, and readability.

For our demo day, Kate and I dabbled with ViewComponent, and I presented on the result. Enjoy!
Shine bright like a ruby(-ist)
By: Brian Li
Tags: Ruby on Rails, Ruby

While it’s true that Ruby doesn’t get as much love as Javascript or Python, Ruby is still getting updates on a yearly-basis. There’s so much to love about Ruby so don’t feel deterred at all from learning Ruby!

So why Ruby???

When Matsumoto created Ruby, he created with a certain purpose “to be productive, and to enjoy programming, and to be happy.” Matsumoto had several principles during his creation. He believed that programming should be easy for us and that we should be in control of what we type, not the computers.

The legend himself

He also followed the principle of least astonishment (POLA), meaning he wanted to minimize confusion as much as possible for the programmers’ enjoyment.

Ruby is also great due to it’s extensiveness on object-orientation. Every value you write in Ruby is an object so it’s easy to hold references to these values.

There been some direct comparisons on how similar Ruby is with Python, so changing to popular language may not be so hard after all. Lastly, Ruby on Rails is a must if you are ever going to use Ruby.

“We are the masters. They are the slaves.” -Matsumoto

Ruby on Rails Express

If you ever heard about Ruby, more than likely you’ve heard of Rails too. Similar to PB&J, these two words pretty much come in a package and you should never forgot to use one or the other.

So what is Ruby on Rails? Ruby on Rails is a server-side web framework that uses the MVC (Model-View-Controller) to help ease web development better. To explain the MVC, it starts with the user that interacts with the view which presents data and handles user interactions. Next, the view tells the controller of a specific event that might have occured. When that event goes through, the controller then updates the model of what has changed. The model then tells the view component of the change in data and so in response, the view will grab the data from the updated model and render the new data onto the view component.

The MVC Cycle

With the design of Rails, the creator, David Heinemeier Hansson, wanted to emphasize on two principles: Covention over Configuration (CoC or Coding by Convention) and Don’t Repeat Yourself (DRY). The CoC principle describes development through programming conventions vs user defined configurations. The DRY principle tells that the user should not repeat their code to help reduce repetition and to avoid redundancy.
Rails實作devise套件
Tags: Ruby on Rails, Ruby, 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
Can I set a Model attribute to array in Rails?
By: Yulia Y.
Tags: Ruby on Rails, Ruby Attributes

Recently I was coding something in Ruby on Rails and I came to a question if I can have array as an attribute for my Model. I started look for Rails documentation and found all available datatypes for Active Records migration

:binary , :boolean , :date , :datetime , :decimal , :float , :integer , :bigint , :primary_key , :references , :string , :text , :time , :timestamp

I also found that you might use a type that is not in this list as long as it is supported in your database. Database that I primary work with is PostgreSQL. It supports many others data types, like :array and :hstore (which is a hash). So yes, we can store multiple values (arrays or hashes) in one column.

Here is how the migration file should look like in order to get attribute as array:

class CreateStore < ActiveRecord::Migration

def change

create_table :stores do |t|

t.string :name

t.string :address, array: true, default: []



t.timestamps

end

end

end

If you want the default value to be an empty array set the default to [], otherwise, the attribute is nil , until you give it a value.
Project Planning & Construction (With Ruby On Rails)
By: Jane Venter
Tags: Database Design, Planning, Ruby on Rails, Activerecord, Relational Databases

Photo by Dan Burton on Unsplash

When I am starting a project, I first answer questions about what my application should do: a minimal viable product, and what data I would like to store.

I am going to assemble the building blocks to create a backend web application that can have users sign in and share content, or posts.

https://guides.rubyonrails.org is where to go to get started building your Rails App if you are new to using Ruby On Rails. To create a Rails application that is backend only make sure to add ‘- -api’ to the end of the following command:

rails new project --api

If I want a web application to have potentially many users I can create a User object class. I will probably want my users to have a name to be displayed to others, a password to verify authenticity, and an email to contact the user.

We can write migrations to modify the schema. The following will add a table to the database with the columns password_digest, name and email.

rails generate model User password_digest:string name:string email:string rails db:migrate

Besides attributes that belong to an instance of the user class, I will want a user to have access to certain data that is personal to them, as well as the ability to create and manipulate data.

I want to set up the schema so that a user can have relationships with other objects.

What if the user can create many posts? I establish a has_many relationship, because our user has the ability to create more then one post.

rails generate model Post link:string title:string public:boolean category_id:integer

A post could belong to a category, and a category could have many posts. Therefore we can give the attribute of category_id to a post.

rails generate model Category name:string

In our models we need to specify what relationships exist. In the User model:

has_many :posts

In the Category model:

has_many :posts

In the Post model:
Compare three approaches to integrate React to Rails app
Tags: Ruby on Rails, React, Ruby, Rails

I am planning to build a side project these days. My most familiar framework is Rails and this time I want to practice how to integrate React to Rails.

Surf on the internet, I summarize three ways to get Rails and React working together.

The Gem way

After Rails version 5.x, we can easily integrate React to Rails by simply adding gems likes react-rails or react-on-rails to reach this goal.

Pro

Save a lot of time to setup

Con

Difficult to develop a mobile app

The API way

Create completely separate Apps for React Web Application and Ruby on Rails Application. Both of them should be located under the same root folder.

Running these two under the same address but different ports. For example, Ruby on Rails app will be hosted under 127.0.0.1:3000, and our React app will be 127.0.0.1:3001.

For this approach, the requests will be done by the same address to help us achieve a faster response.

→ my_application

→ frontend

→ backend

Pro

Easy to develop a mobile application

Easy to scale

Con

Most complicated way to implement

The inner API way

Instead of creating a completely separate folder for React app, nesting it into our Rails app. The folder structure will be like this.

→ backend

→ app

→ frontend

Pro

Easier to approach compared to the above API way

Con
Primary Keys as UUIDs: A Guide
By: Kevin Gleeson
Tags: Uuid, Ruby on Rails, Primary Keys, Ruby, Guides And Tutorials

Step 2: Set UUID as Primary Key Type

As mentioned earlier, our primary keys are set to sequential ids by default. Let’s see how we would handle changing this in one of our models.

Now when we’re creating our table, we’re going to establish that the id for each report will be a uuid. In this model relationship, a Device has_many Reports, so we’ll need to make sure to say that our foreign key is also a uuid instead of the typical t.integer. Now when we migrate our models and look at our schema.rb file…

sorry that this is so tiny!

…our default for our id will generate a random uuid. Now our reports and devices both have uuids!

A Single Caveat

As you can see, it’s really easy to establish UUIDs as your primary keys. There is one drawback and that’s that the order of your instances will likely become out of order. This is because Rails will sort UUIDs alphabetically, so if your second instance starts with ‘a’, it will likely show up as your first instance. Numbers, in this case, go after letters, so you’ll need to figure out a way to re-sort your instances by something else (created_at, maybe?)

If you want to know a little bit more about those next steps and to check out the resources I used for this blog check them out here and here.
Getting started with Ruby on Rails: A blog app (Part 2)
By: Brian Ngeywo
Tags: Beginner Rails, Rubygems, Devceld Backend, Ruby on Rails

Add authentication with devise

add devise gem to your gemfile

gem 'devise'

run bundle install to install devise into your app, and complete the installation using the following command. you can learn more about the devise gem here.

rails generate devise:install

now lets add users into our app, as for me I will call them authors

rails generate devise author

and well now migrate our database

rails db:migrate

in our app, we only want authors(users) who have logged into our app to post articles, so we need to add some restrictions. at the very top of our app/controllers/articles_controller.rb, add this line.

before_action :authenticate_author!, except: [:show, :index]

Its important for it to be at the top of the file as rails follows top to bottom order when it comes to executing controller restrictions. here we are restricting every other action except showing list of articles or reading an article.

2. Add associations

here we going to link our authors with articles. typically, authors can post multiple articles, but an article can only have one author. so we have a one-to-many relationship in our case.

in app/models/Article.rb

class Article < ApplicationRecord belongs_to :author end

in app/models/Author.rb

class Author < ApplicationRecord has_many :articles end

create a new migration from your terminal to add author_id to article.

here will will add author id, which will be an integer

rails g migration add_author_id_to_articles

now in root folder/db/migrate, you will see the migration file. mine looks like this

class AddAuthorIdToArticles < ActiveRecord::Migration[6.0] def change add_column :articles, :author_id, :integer end end

Don’t forget to run the database migrations with rake db:migrate

now in our articles controller, edit the create action, and add this line.

# POST /articles.json def create @article = Article.new(article_params) @article.author = current_author #add this line respond_to do |format| if @article.save format.html { redirect_to @article, notice: 'Article was successfully created.' } format.json { render :show, status: :created, location: @article } else format.html { render :new } format.json { render json: @article.errors, status: :unprocessable_entity } end end end

here we are associating a new article with the current logged in user. with this, you can call author.articles, and it will return a list of all articles by the user.

i wont go into design, but i have attached my final app screenshots. you can also find this code on GitHub.
How Relevant is Ruby on Rails Development For Startups?
By: Shravan Bhan
Tags: Ruby On Rails Development, Ruby On Rails Developers, Ror, Software Development, Ruby on Rails

Shortlisting a platform for further course of development completely depends upon the factors you consider are most important to you. If you give utmost importance to factors such as cost-effectiveness, secure environment and such other factors then ROR is definitely a better way to go for. Still, we will be discussing the advantages and disadvantages of going ahead with Ruby on Rails Development below:

ruby on rails development company

Advantages of Ruby on Rails Development

Flexible — Ruby on Rails is extremely flexible as it is an open source platform. You can find enough libraries for this platform that are ready to use thus saving a lot of time and costs. In the times where we have to start the project in a quick span of time, ROR can ensure the starting of project in least possible time.

Security — Ruby on Rails is an exceptional platform when it comes to the secure environment. Though the feature of security isn’t standard so you need to make sure that the developers follow a safe product development cycle.

Support From Expert — The experts in the Ruby forums are active in most of the times and provide updates on dails basis. They always work extensively to keep the platform secure and reliable.

Quality Architecture — This platform allows the developers to develop very simple APIs with help of restful architecture. This ensures in user getting a better experience at the end.

Faster Development Process — Development on Ruby is way much faster when compared to other frameworks. This factor is exremely beneficial for the startups as they have limited resources at their disposal.

Used Extensively — Even in the present times a lot of companies in the market are leveraging the Ruby on Rails Development for their softwares. Twitter, Airbnb, Couchsurfing are all already using Ruby on Rails.

Still, if you’re facing some sort of confusion you can always reach Nanotech Softapp as they provide free consultation in their web development services. So even now, ROR development is relevant for startups.
The time I quickly needed lots of fake user profiles (for an article)
By: Stephan Eberle
Tags: Ruby on Rails, Programming

When I was working on my last Medium story (here) I was first using our production database to show off some functions of a web application.

While the tool is used internally at New Work SE this would have worked for an internal blog or Slack post, however this is a totally different story for showing your workplace with actual people, where they sit, with whom to the public, without their consent or them even knowing.

So I needed to find a quick way to replace all profile images and names with fake data. Working with Rails I use factory_bot_rails (link) frequently to generate fake data, but I am missing a fitting avatar image when using this Ruby gem.

I started looking around and found Ramdomuser.me,which is a web app that profiles fake user profiles with logs of fake-data attributes and it even provides an API to pull multiple profiles at once.

The first thing I did was look at the actual response JSON from the service to orient myself:

Excited as I was, I really just needed to replace the avatar images and names with the ones from the fake profiles. After some further reading the API documentation I added some parameters to the query so the response got smaller.

The final result is this rake task:

Pulling fake user profiles and changing actual users to be anonymous

As you can see there is no magic and the code however naive works flawlessly with our 2.6k users. I added the progress_bar Ruby gem for nicer output (it will also calculate when the job is done).

One little aspect here is the fact that I do not need to download the profile images into local temp files to again upload them to the database.

The User model that is used has a paperclip attribute for the user image and with a little extra method one can use the URI module to download and assign the avatar image file to the User.image like so:

Using URI to download and assign a profile image from a URL

This is in no way very sophisticated or elegant, but it gets the job done and I didn’t plan on build this feature in the first place and definitely not while writing a blog post. Again Ruby On Rails and its ecosystem made something complex easy to use so that I didn’t lose focus too much and was able to just like that create some “fake user” screenshots.

Thank you for reading and thank you, Randomuser.me, for providing an easy-to-use API service!
How we fight Covid-19 at the office with Rails
By: Stephan Eberle
Tags: Ruby on Rails, Covid 19, Office, Rails

When the pandemic hit early this year it was almost certain that we needed to close the office. With a company of ~1800 people in multiple office buildings around Europe there was only question of when we were affected, not if, and how to react and move forward.

When the first case of a Covid-19 positive co-worker was registered in our Hamburg office we immediately closed down our location and started working from home. Everyone was now affected by the office not being available as a place to work, collaborate or meet colleagues. You can read more about this switch from my colleague Björn Rochel.

While I was in a lucky position to have a spare room to myself as a home office a lot of colleagues were not that fortunate and again others did not want to be alone the whole day in their apartment and preferred to have face-2-face contacts. So the thought of how to make the offices available to our colleagues in the safest way possible was born.

Luckily we already use a tool called the XING Locator: Think of it like Google Maps, but indoors. It provides a floor plan for almost all our office locations (Hamburg, Vienna, Munich, Barcelona, Porto, …) and all the floors are prepared in a way that makes it possible for every colleague to find their physical desk on the map and “claim” it to be theirs and thus telling everyone else where to be found.

The tool also covers coffee makers (really important), conference rooms and soccer tables (also kind of important), utility rooms and showers, rest rooms, … you get the point. You can find out more about its early days by reading this article from my Locator co-creator Jan Habermann .

The 4th floor of our Metropolis office in Hamburg (part of it) as shown in the Locator

As the pandemic became more and more one of the deciding factors of our lives we needed to adhere to certain rules: Keeping distance to each other (aka “social distancing”), wearing masks indoors, regularly wash hands and open windows (“Lüften” is a form of art).

As the core of the Locator basically is a GIS application, the “distancing” is something we thought we could take care of.

The first measure that was defined was to make it mandatory for every employee wanting to use the office to claim their desk in the morning.

We helped a bit by auto-clearing all desks every night, because until then you could claim your desk and it would stay yours for as long as you did not „un-claim” it (or someone else removed your claim for housekeeping). This way we would know the claims were legit and people were actually at the office on a specific date.

By disabling desk-claiming for specific desks we can ensure minimum distances between colleagues as shown.

As we only stored the active claims in the database we needed to add some history to enable contact tracing in retrospective (as you only know five to six — and up to 14 — days later that you’re Covid-19 positive).

The timeline is available for “admin” users so one can see the current “load” of each location.
Hire Ruby on Rails Development Company
By: Sweni Shah
Tags: Rails, Web Development, Web App Development, Ruby on Rails, Ruby

Hire Ruby on Rails Development Company

Introduction:

Are you in the hunt for hiring the top Ruby on Rails development company for your new or existing product? If it’s yes, then you have stopped at the perfect place. I will surely guide you with all the requirements and the details for hiring Ruby on Rails developers from the Ruby on rails development company.

Let’s get started by introducing the world’s best Ruby on Rails development company.

Bacancy Technology is splendid and recommended Ruby On Rails Development Company. It provides the best quality services to all the clients globally, mainly in the USA, Canada, Australia, and the UK.

Bacancy Technology is into this business and has been established since 2011. There are 8+ years of experience in Ruby on Rails Development company. Hiring Ruby On Rails Developers for making web applications helps in reflecting leading-edge solutions to the business. Most developers are very expert in MVC architecture, OOPS concepts, JSON Standards, HTML, CSS, JQuery, and many more.

If you are highly focused on hiring RoR developers for the projects, then Bacancy Technology is the best choice for the business. We give extraordinary services for your business.

You can hire Ruby on Rails developers hourly or monthly basis, depending upon your RoR projects.

The hourly charges would be $22, and monthly costs would be $2800 for 5 years of experience with senior developers and 160 hours per month. Also, monthly $14000 cost for a custom team of 5 skilled developers +1 dedicated QA +1 dedicated PM.

Technology Stack for Ruby On Rails

So I hope that you all are very clear that Bacancy Technology developers are superior at delivering the finest RoR solutions.

Working with Bacancy Technology, you can save 40% on Maintenance, Development, and Support Cost. We have also started 15 Days Risks-Free Trial.

Yes, you have heard the correct word, “15 Days Risks-Free Trial.” It is completely free. Here we grant a free period, and it also helps to evaluate the quality of code on-time delivery and communication. You can try by hiring Ruby on Rails development company for the trial resources and get the best and satisfactory result.

I hope you will like our Ruby on Rails developer’s skills and knowledge. Get free price estimation from expert RoR developers.