Synthesize common gems in Rails – Part 2: Faker and Friendly Id

Tram Ho

In this section, I will introduce 2 gems that are very familiar to Ruby developers and moreover, I think these are also gems that will help newbies in learning Ruby on Rails.

I. Gem Faker

1. Introduction

Faker is a new gem to Ruby on Rails developers, and almost every Rails project with Unit tests uses this gem. So you can call this the gem that you need to know if you are looking to learn to code with Rails

2. Installation

Of course, to install, you have to “register documents” in gemfile and then run the command bundle install gem 'faker'

Note: If you get a version error like this uninitialized constant Faker::[some_class] then you change the line above to

gem 'faker', :git => '', :branch => 'master' for sure

3. Use

Try opening the rails console and running these commands

Easy to understand is not it

Some other uses

In case you have used up all the (unique) names of the gem it will not let you create any further and return the error Faker::UniqueGenerator::RetryLimitExceeded . At this point, you need a command to clear the values ​​used to fake

In addition, Faker also supports to fake some other things such as:

For more reference, usually I only use to fake some things in the Default section, when I tested this article, I found that the fake was quite widespread.

See more here:

II. Gem Friendly Id

1. Introduction

If you pay attention to the URL of the websites on the Internet, you will see that it is quite different from the URL in the project that I do by myself. For example, your URL usually has id http: // localhost: 3000 / post / 1 But the URL on the internet is

A URL like this is called a friendly url. Looking at the url can also know roughly some information of that page instead of just an id

2. Installation

Register “papers” in gemfile gem "friendly_id" and then chant bundle install spell

Add column slug to the table that you want to use friendly id and then run migrate to update DB.

For example, you have table posts with column title . On the URL you want to display the title instead of the id of that post as usual. The mechanism of this gem is to convert the title to this-is-title form and save it to the column slug. Every time it displays on the url, the slug is displayed

Next, in the Post model you add the following lines

So, you have designated to take the title as a slug

3. Use

Whenever we call Post anywhere in the project, instead of Post.find id we change to Post.friendly.find id.

We try to create a Post.create! title: "example post"

Above the URL we can easily access that post with the URL http://localhost:3000/posts/example-post.



Hope this article will help you in the process of approaching and learning Ruby on Rails. Thank you for reading

Share the news now

Source : Viblo