You have noticed a file called Gemfile.lock in your Ruby on Rails application and have wondered what is it, how it works. The file may have even given you trouble when you attempted to push changes to source control. In this article I will discuss what exactly this Gemfile.lock file is and how it helps your Ruby on Rails application.
Gemfile.lock
If you actually opened the Gemfile.lock file you probably saw a bunch of text as below:
The Gemfile.lock file stores a complete snapshot of every version of every gem your Ruby on Rails application uses. The reason for this is simple. Let’s say you are using Rails 4.1.6 and Rails 5.0 comes out. You don’t want this new version to be pushed to your application during the next update. Why? You developed your application using the old version, and the new version may not be compatible with your code. That is why it is also important to check your Gemfile.lock into source control with the rest of your application.
The Gemfile.lock file not only stores exact version information, but bundler USES that version information to rebuild the snapshot on production. If you take a look at your Gemfile (not Gemfile.lock) for example you will see the following line:
1
gem'coffee-rails','~> 4.0.0'
Bundler knows that you used version 4.0.1 during development. When this file is pushed to production and you run a bundle install –deployment, bundler will recreate a snapshot of all of the gems that you were using on your development machine.
When does this file get updated? Any time you add a new gem to your gemfile (and run a bundle install) or type bundle update [gem name] your Gemfile.lock will get updated. If you attempt to update the version of a Gem in your Gemfile, bundler will warn you to do a bundle update the next time you try to run a bundle install.
In this case, you would be unable to proceed until you run bundle update coffee-rails, which would then update your Gemfile.lock to include the new version of coffee-rails. This is also why it’s disastrous to run a bundle update without specifying a gem. Bundle update rebuilds the entire Gemfile.lock file from scratch, blowing away all of the old versions and replacing them with the latest ones allowed by the Gemfile.
So far so good, the Gemfile.lock file is designed to save headache and frustration when deploying your application both across development machines as well as to production. It’s always a good idea to make sure that you check this file into source control and be aware of how it works. That’s it! See ya!
Endless scrolling allows a website to let users avoid having to click page links or pagination in order to load additional pages of content. It is used by a number of sites such as Pinterest in order to enhanced the user experience. This article will show you how to implement endless scrolling in your Rails application. Let’s run through this with me.
Create Rails Project
To create a Rails project; open up your terminal and type commands below:
1
railsnewendless_scrolling-dmysql
Setting up
Ruby on Rails endless scrolling uses the will_paginate gem to manage paging. This has a couple of advantages.
First, if your endless scrolling code doesn’t work properly or is disabled, the pagination links themselves will still be present and allow the user to page.
Second, the will_paginate gem provides us with the pagination functionality itself so that we do not need to reinvent the wheel.
To get started, add the will_paginate gem to your Gemfile file.
Gemfile
1
gem'will_paginate','~> 3.0.7'
Then run a bundle install to install the gem:
1
bundleinstall
we will create a simple Post model with the fields title, and body. In addition, we will create a simple Posts controller with an index method. Run the commands below to create these items:
Then we need some seed data to play with. Open up your seeds.rb file and add in the code listed below. This code will create 100 posts for us to play with:
seeds.rb
12345
(1..100).eachdo|i|Post.create!(title:"Lipsum Post #{i}",body:%{ Lorem ipsum dolor sit amet, consectetur adipiscing elit. In feugiat purus dapibus fermentum sagittis. Fusce in tempus felis. Phasellus a erat ut lorem lacinia bibendum. Vivamus viverra facilisis neque, in scelerisque urna pharetra vel. Donec a est mauris. Integer eget metus quis eros egestas elementum. Integer bibendum risus hendrerit dapibus tempor. Fusce placerat in orci vitae tincidunt. })end
Then run rake db:seed to create the seed data:
1
rakedb:seed
Then open up your Posts controller (app/controllers/posts_controller.rb) and modify it so that it looks like the code listed below:
Then let’s create the post partial. Create a file called _post.html.erb (app/views/posts/_post.html.erb) for your Posts controller and add in the code listed below:
If you were to start a rails server at this point, you’d see a typical paginated list of posts. Now it’s time to add in the javascript that will make endless scrolling work. Open up your application.js (app/assets/javascripts/application.js) file and add in the code listed below:
The code works by watching the window’s scroll event. When the user scrolls past the specified threshold, more posts are loaded using AJAX. That’s it, thank you!. See ya! :)
Sometimes we need to programmatically generate text in Ruby on Rails. We may not have any data available to play with or we may need text in order to mock up the user interface. In this article I will cover 2 different methods of generating random text. Let’s run through this with me.
Random Letters
If you just need fill text, you can add this helper to your application helper (app/helpers/application_helper.rb):
The helper has 1 required argument is length, which determines the length of the string. To generate a random string of 200 characters, call the helper like below:
1
<%=random_string(200)%>
Forgery Gem
The forgery gem provides a great way to generate random data. Not only can forgery generate random words (based off lorem ipsum), but it can also generate random email addresses, and much more. To use forgery, just include the forgery gem in your gemfile:
Gemfile
1
gem'forgery','0.6.0'
Then run bundle install to install the Gem.
After installing the Gem, you are ready to go to generate words:
1
<%=Forgery(:lorem_ipsum).words(100)%>
To generate a random email address:
1
<%=Forgery('internet').email_address%>
So far so good, I hope all you guys enjoy it. See ya! :)
DropzoneJS is a javascript library for allowing multiple file uploads via AJAX. It features drag and drop support, folder support, and much more on browsers that support these features.
In this article I will show you how to implement multiple images files uploads directly to paperclip using DropzoneJS. Let’s run through this with me.
Create Rails Project
To create a Rails project; open up your terminal and type commands below:
1
railsnewdropzone-dmysql
Add Gems
We will add two gems to our Gemfile. dropzonejs-rails gem is a helper gem that integrates DropzoneJS into our Rails app. paperclip for processing image uploads.
Open up your Gemfile and add in the lines listed below:
Gemfile
12
gem"paperclip","~> 4.2"gem'dropzonejs-rails'
Now let’s run a bundle install to install the gems:
1
bundleinstall
Create a Image Model
Now we will create a model to store our image information for Paperclip. Run the command below to create the image model and migrate the database:
12
railsgmodelimageavatar:attachmentrakedb:migrate
Then add some code to Image model to tell paperclip we want to have an attachment attached. Open up your image model (app/models/image.rb:) and add the code listed below:
Create a Images Controller
Then create an Images controller which will be used to display and allow the upload of our images. Run the command below to create this controller:
1
railsgcontrollerimagesindexcreate
Then update our routes file to set up the routes for our images controller. Open up the routes file (config/routes.rb) and modify it:
Then modify our Images controller to add logic to handle the file upload as well as listing each of the images. Open up the Images controller (app/controllers/images_controller.rb) and modify it:
Well, then create our views. First let’s create the index view (app/views/images/index.html.erb). Open up your index view for the images controller and modify it:
index.html.erb
123456789101112
<h1>MyImages</h1><%= form_for(Image.new, html: { multipart: true, class: "dropzone"}) do |f| %> <div class="fallback"> <%= f.file_field :avatar %><br> <%= f.submit "Upload my Avatar" %> </div><% end %><div class="index"><%=render"index"%></div>
Then we need to add some JavaScript to tell Rails how to handle the remote ajax file processing that we will do using dropzone. Create a view called app/views/images/index.js.erb for your images controller and add the code listed below:
Then create the partial that we reference in the previous code. Create a new partial called app/views/images/_index.html.erb for your images controller and add the code listed below:
_index.html.erb
12345
<% @images.each do|image|%> <div class="img-thumbnail"><%=image_tagimage.avatar.url(:thumb),alt:image.avatar.url(:thumb)%> </div><% end %>
Then modify our application.css and add the dropzone css require. Open up your app/assets/stylesheets/application.css file and modify it:
So far so good, if you start your Rails server and navigate to http://localhost:3000 you will notice that you can drag and drop images onto the app. On certain browsers, such as Google Chrome, you can even drag and drop one or more folders of images onto the dropzone placeholder and have them upload. In addition you can also click the dropzone and select a file via the file selection screen. That’s it! See ya! :)
Well, in the previous article I’ve shown you ”Install Git on Linux/Ubuntu”, and in this article I want to show you “Create Ruby on Rails project and using Git”. Let’s run through this with me.
Create Ruby on Rails Project
Type command below to create a Rails project:
1
railsnewtodo-dmysql
Initialize Git
Type command below to initialize git:
12
cdtodogitinit
Ignore File/Dir
Git uses file .gitignore to determine which files and directories to ignore, before you make a commit.
.gitignore file should be committed into your repository, in order to share the ignore rules with any other users that clone the repository.
Type command below to create a .gitignore file:
1
vim.gitignore
Then type file/dir or content that you want git to ignore:
Overview
Git is a free and open source distributed version control system with an emphasis on speed, data integrity, and support for distributed, non-linear workflows.
Installation
Use command line below to update local package index and then install the packages:
Setting Up Git
Now you have git installed, you need to do a few things so that the commit messages that will be generated for you will contain your correct information.
You need to provide your name and email address by using git config because git embeds this information into each commit you do. You can go ahead and add this information by typing:
You can see all of the configuration items that you have been set by typing command below:
1
gitconfig--list
What you will see:
12
user.name=YourNameuser.email=youremail@domain.com
The information is stored in the configuration file, which you can optionally edit by hand with your text editor like this:
1
vim~/.gitconfig
123
[user]name=YourNameemail=youremail@domain.com
So far so good, now you should have git installed and ready to use on your system. To learn more about how to use Git, check out these: www.try.github.io
Ruby on Rails connect to Multiple Databases and using ActiveRecord with multiple databases, it’s really simple take it easy. Let’s run through this.
Rake Tasks
Well, I want to handle migrations for two databases, so I need two separate Rake tasks to handle that:
123456789101112131415161718
desc"Migrate the database through scripts in db/migrate directory."namespace:dbdotask:migratedoRake::Task["db:migrate_db1"].invokeRake::Task["db:migrate_db2"].invokeendtask:migrate_db1doActiveRecord::Base.establish_connectionDB1_CONFActiveRecord::Migrator.migrate("db/migrate/db1/")endtask:migrate_db2doActiveRecord::Base.establish_connectionDB2_CONFActiveRecord::Migrator.migrate("db/migrate/db2/")endend
My first task is db:migrate that delegates out to db:migrate_db1 & db:migrate_db2.
Each of those establish a connection to the database and then runs the migrations from their own separate folders. This allows you to store migrations in separate folders so you can easily manage them.
The migrations are exactly the same as normal.
Database Connections
In order to get those migrations to work, I need to configure the database connections. I’m going to define everything in the database.yml just like normal, but with a different naming convention:
Take a look at what’s going on:
- I set the database configuration to use. You can just use Rails.env here instead of ENV[‘ENV’].
- I load up the database.yml config and parse it with YAML.
- I grab the configuration from the file for each db and the correct environment that I’m running in.
Connecting Models
When I’m working with multiple databases, I like to explicitly setup the connections inside the models themselves instead of inheriting from ActiveRecord::Base and using subclasses.
Well, All you really need to do is load the configurations, establish the database connections, and setup the migrations to load from a specific directory for each database.
In software development, using a framework is almost a rule for fast, clean, easy readable and standardized coding. Chicago Boss (http://www.chicagoboss.org)is a framework that is heavily inspired by Rails. Set up and use Chicago Boss is easy as falling off a log. Chicago Boss allows you to code with the aforementioned standards in Erlang. Plus, offers conveniences of modern web development, including WebSocket and Comet. Basic features of Chicago Boss listed below:
- 100% asynchronous I/O
- Support for Erlang and Elixir code
- BossDB: Database connection layer with an advanced ORM which with built-in support for Mnesia, MongoDB, MySQL, PostgreSQL, Riak and Tokyo Tyrant
- BossCache: Database caching layer
- BossMQ: Cluster–wide, channel–based message queue
- BossRouter: URL router
- BossSession: Session storage layer
- BossNews: Event listener, model event system
- BossMail: Built-in email server
- Django and Jade template support
- Very clean controllers as result of pattern matching
- Auto document generation for models
- An useful admin interface
- Automatic code reloading
Installation
This short guide will help you get Chicago Boss installed and working on your system. Chicago Boss generally isn’t installed to global system path. Typically, Chicago Boss will be copied to a development directory in your path.
Requirement
Chicago Boss is written in the Erlang programming language, so naturally you will need to install Erlang on your system. You may remember my previous article post about Install Erlang Using Repository on Ubuntu.
Enter the New Project Dir and Run the Development Server
12
cd../project_name./init-dev.sh
Enjoya
Point your browser to http://localhost:8001
If all is well you will see a forbidding error message about the requested template — not to worry, the new project is empty so there is nothing to serve.
The communication model (among processes) in Erlang is message passing. Erlang processes share no memory. The way that processes communicate is via (asynchronous) message passing. Every process (even the shell) holds a mailbox queue where incoming messages are placed until received by the process. Message passing is asynchronous because the sending process does not block on send. On the other hand, receiving a message in Erlang is a blocking operation.
Characteristics
In this subsection I will describe some of the characteristics of message passing in Erlang.
Asynchronous
Message passing in Erlang is a non-blocking operation.
Data Copy
The message’s data are copied from the sending process to the receiver’s message queue, so the receiver gets a fresh copy of the data.
Ordering
Erlang runtime guarantees that if two messages are sent from node A to node B and both are delivered, then the ordering of these messages is kept (because ordering).
Successful Send
The send operation always succeeds (even if the target is a non-existing process) and evaluates to the data sent. An exception is when trying to send data to a non-existing registered process.
Sending Messages
Erlang uses the exclamation mark (!) as the operator for sending a message.
As I have mentioned before, the shell is nothing more than a process. As a process, it has a message queue. In order to print and empty the shell’s message queue we can use the flush/0 BIFs.
Erlang uses pattern matching for receiving messages (same as in function clause selection and the case statement). The receive statement is used to deliver messages from the message queue.
Receiving Order
The message processing is done in a FIFS (First In – First Served) order. Every incoming message is placed in the tail of the process’ message queue. When a receive statement is meet the following processing happens:
1. The first message (head of the message queue) is pattern matched against the first receive clause. If match, execute the clause’s body, else go to the next step.
2. The same message is pattern matched against the second (if any) receive clause. If match, execute the clause’s body, else go to the next step.
3. …
4. The same message is pattern matched against the last clause. If match, execute the clause’s body, else go to the next step.
5. The same iterative process starts again from step 1, but now with the next message from the message queue.
The message (if any) that is delivered through receive is removed from the message queue.
Timeout
Receive is a blocking statement; it blocks until a message that matches one of the clauses is placed in the incoming message queue. Erlang allows the programmer to explicitly unblock the receive statement using a timeout (if a matching message is not delivered until the timeout expires). The complete format of receive statement, including the after construct.