神刀安全网

10 Ruby on Rails Gems for Web Development

I have been programming on Ruby on Rails for many years and have solved a variety of rather complex tasks using this excellent framework. Based on my experience, I put together a short list of gems which I consider to be the most useful. In this article, I would like to share this list and show you how to find the helpful gems for RoR.

Unfortunately, the format of gemís specification does not include defining categories and tags. Thatís why, when searching for gems to do certain tasks, we may only hope that the author of the gem has mentioned some keywords in the description. You can find many gems on rubygems.org or github.com. The searching can be done by description (on GitHub, you also have to select Ruby from the list of languages).

Another thing worth being mentioned is the Ruby Toolbox . It allows searching for gems by categories and popularity. But do not rely only on this source because the author of Ruby Toolbox adds new gems manually.

Foreigner

This gem helps to create foreign keys for tables. It is very easy to use. You may simply put it to Gemfile and it will add two new methods to your migrations: add_foreign_key and remove_foreign_key . Also, you will be able to add/delete keys right from create_table and change_table with foreign_key and remove_foreign_key methods.

Letís imagine that we need to add a key from the comment table to the posts table. We can do it the next way:

class CreateComments < ActiveRecord::Migration def change create_table :comments do |t| # … t.references :post # ... t.foreign_key :posts end # … end end

These methods have some extra options, e.g. name, column, dependent. You can read more about them in documentation .

Someone may say that it is not actual for new versions of Rails, but itís only starting from version 4.2 (where such functionality is already available out of the box). In all other cases, in my opinion, this gem deserves to be in the list of useful ones.

Link to GitHub

letter_opener

A simple but very helpful gem. In fact, it is a plug for saving emails in files instead of sending them. To activate this gem, you have to set letter_opener as the delivery method in the appís configuration (for example in config/enviroments/development.rb).

config.action_mailer.delivery_method = :letter_opener

Bingo! Now all outgoing messages will be stored in /tmp/letter_opener folder and new emails will be previewed in browser right after sending. It is easy and practical.

Link to GitHub .

Kaminari

This gem allows to easily create paginators of any complexity. Kaminari supports several ORMs (ActiveRecord, Mongoid, MongoMapper) and template engines (ERB, Haml, Slim).

Kaminari does not embed in basic classes: array, hash, Object and ActiveRecord::Base.

To start using Kaminari, it is enough to put it in Gemfile. After that some functions will become available, e.g. page, per and padding. Now you can effortlessly convert your array into a paginatable one with the help of Kaminari.paginate_array method and then lots of useful pagination features will become accessible.

@paginatable_array = Kaminari.paginate_array(my_array_object).page(params[:page]).per(10)

The default configuration can be made in Kaminari.configure initializer. default_per_page , max_per_page, max_pages – this is just a brief list of options which can be set.

Besides, the pagination can be configured individually for each model:

class User < ActiveRecord::Base  paginates_per 50 end

If you need to customize the paginator, you can create templates by running a generator:

% rails g kaminari:views default # -e haml - if you want to use  HAML template engine.

The templates will be created in app/views/kaminari/ and now you can easily edit them.

Localization (I18n) and labels, themes and friendly urls, as well as other useful options can be found in the documentation for this gem.

Link to GitHub .

CarrierWave

With CarrierWave you are able to upload any files from your RoR application. All you need to do is:

Create an uploader:

rails generate uploader ProductPhotoUploader

Add some options:

class ProductPhotoUploader < CarrierWave::Uploader::Base include CarrierWave::MiniMagick  storage :file  def store_dir "product_images" end  def extension_white_list %w(jpg jpeg gif png) end  def filename Digest::SHA1.hexdigest(self.read) + File.extname(original_filename) end end

And you can already use uploader to save files in storage.

uploader = ProductPhotoUploader.new uploader.store!(my_file)

CarrierWave also allows storing files in temporary storage, filesystem, and even in the cloud.

You can connect CarrierWave uploader to AR (there are adapters for other ORMs as well) model and save your files by saving a record in the database:

class Retailer < ActiveRecord::Base mount_uploader :logo, RetailerLogoUploader end  retailer = Retailer.new File.open('logo.jpg') { |f| retailer.logo = f } retailer.save! retailer.logo.url # => '/url/to/logo.png'

Also, it is possible to change the quality of an uploaded image, crop it, encrypt files and many more on the fly, while uploading them – all this can be found in the documentation.

Link to GitHub .

Urlify

A simple and easy to use gem for converting diacritic strings to ASCII-safe URI strings. After installing this gem, you can call the urlify function for any string and it will immediately be converted to a URI-compatible equivalent.

URLify.urlify('Kj?le Test') #=> kjoele_test

Or:

config.action_mailer.delivery_method = :letter_opener

0

Link to GitHub .

WickedPdf

It is a plugin for RoR, which helps to generate PDF from html. After adding this gem, you need to do the next steps:

Create the initializer:

config.action_mailer.delivery_method = :letter_opener

1

Register mine-type:

config.action_mailer.delivery_method = :letter_opener

2

Take into account that this gem uses wkhtmltopdf utility and the path to this utility should be specified in the gemís settings.

config.action_mailer.delivery_method = :letter_opener

3

Link to GitHub .

Countries

If you have faced with a task which requires having different information about countries, this gem will provide all data you need to solve it. There is a search by country name and by region, currency information (symbol, code), various formats of phone numbers, coordinates, etc. All that is needed after installing it is to create a country object (or get it from a global helper) and then you can draw the necessary information:

config.action_mailer.delivery_method = :letter_opener

4

And this is how to get information about the currency:

config.action_mailer.delivery_method = :letter_opener

5

Or check whether the country is the EU member or not:

config.action_mailer.delivery_method = :letter_opener

6

Here is an example of a search for a country by name and currency code:

config.action_mailer.delivery_method = :letter_opener

7

Link to GitHub .

CanCanCan

This library allows you to conveniently configure authorization in RoR. With its help you can easily restrict access to certain resources. Its convenience lies in the fact that managing permissions is set apart from the user and all permissions are stored in a single place. Thatís why you do not have to duplicate them in your controllers, views or database requests.

The library needs a current_user method to be defined in the controller. So, at first you have to configure authentication (this time I have used Devise, but there are other gems). Then, generate an ability:

config.action_mailer.delivery_method = :letter_opener

8

Specify the user permissions (can/cannot methods) with the commands :read, :create, :update and :destroy (you can find more in documentation).

config.action_mailer.delivery_method = :letter_opener

9

After that, in the views you can use can? and cannot? helpers to check current user’s permissions for given actions:

@paginatable_array = Kaminari.paginate_array(my_array_object).page(params[:page]).per(10)

0

Also, you can use the authorize! method to authorize actions in the controller:

@paginatable_array = Kaminari.paginate_array(my_array_object).page(params[:page]).per(10)

1

Or you can use before filter load_and_authorize_resource which will load the resource and will try to authorize it.

To handle authorization errors you can catch an exception raised by CanCan::AccessDenied in the following way:

@paginatable_array = Kaminari.paginate_array(my_array_object).page(params[:page]).per(10)

2

Additional information can be found in the documentation on GitHub.

Link to GitHub .

Formtastic

This gem provides a great DSL, by means of which, you can very easily create beautiful, clearly readable and semantically rich forms. This DSL is very handy to use: just list the fields in a semantic_form_for block for the required object and you will get a nice form:

@paginatable_array = Kaminari.paginate_array(my_array_object).page(params[:page]).per(10)

3

Here you can also work with nested resources:

@paginatable_array = Kaminari.paginate_array(my_array_object).page(params[:page]).per(10)

4

Nested forms are provided too. You can use a f.semantic_form_for (usual Rails style) but the Formtastic style looks even more beautiful with the :for option.

@paginatable_array = Kaminari.paginate_array(my_array_object).page(params[:page]).per(10)

5

You can easily change the behavior of the input:

@paginatable_array = Kaminari.paginate_array(my_array_object).page(params[:page]).per(10)

6

Create your own input based on the existing one:

@paginatable_array = Kaminari.paginate_array(my_array_object).page(params[:page]).per(10)

7

Or create a completely new input type:

@paginatable_array = Kaminari.paginate_array(my_array_object).page(params[:page]).per(10)

8

Afterwards you can use it with:

@paginatable_array = Kaminari.paginate_array(my_array_object).page(params[:page]).per(10)

9

Formtastic supports an impressive list of input types (select, check_boxes, radio, time_zone, datetime_select, range), basic and advanced localization, belongs_to, has_many and has_and_belongs_to_many associations and many other features, which you can learn from the documentation .

Link to GitHub .

Capistrano

This tool allows executing commands on multiple remote machines in parallel via SSH. This gem has an easy to use DSL. It enables you to define the tasks that will be applied to the machines with the certain roles. It also supports the tunnel connections through a gateway machine.

After turning on the gem, you have to execute:

class User < ActiveRecord::Base  paginates_per 50 end

0

This creates folders with configurations.

If you are going to use different environments, you have to add a STAGES parameter, e.g.: STAGES = local, sandbox, qa, production .

To run a cap-script, use the command – bundle exec cap [environments separated by gaps] [command] . For instance, deploy for the staging environment will look like this:

class User < ActiveRecord::Base  paginates_per 50 end

1

Capistrano DSL is borrowed from Rake. Below is a simple example of the task:

class User < ActiveRecord::Base  paginates_per 50 end

2

See the documentation for all possible parameters, more details about defining tasks, connecting the plug-ins and other things.

Link to GitHub .

Well, we reviewed ten most useful gems for Ruby on Rails and here my story comes to the end. Hopefully, you find this information helpful. Thank you and bye for now dear readers.

原文  https://dzone.com/articles/10-ruby-on-rails-gems-for-web-development

转载本站任何文章请注明:转载至神刀安全网,谢谢神刀安全网 » 10 Ruby on Rails Gems for Web Development

分享到:更多 ()

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
分享按钮