In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Today, I will talk to you about the 10 Ruby on Rails Gems provided for Web development, which may not be well understood by many people. in order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.
Here, the recommended plug-ins for Ruby on Rails's web development include Capistrano and Foreigner.
I have been developing with Ruby on Rails for many years, and I have accomplished a lot of tasks with this excellent framework, some of which can be regarded as very complex projects. Based on my experience, I would like to recommend some gem that I find very useful.
Unfortunately, the format description of gem does not support classification and tagging. So we have to expect the author of gem to list the keywords we need in the description so that we can get better results when searching. You can find a lot of gem on rubygems.org or github.com. You can search by description (you can also select Ruby from the list of languages on GitHub)
Another thing worth introducing is Ruby Toolbox. It allows you to search by category and heat. Don't rely on this tool alone, however, because the authors of Ruby Toolbox add new gem manually.
Foreigner
This gem can help you create foreign keys for the table. It is very easy to use. You simply add it to Gemfile, and it adds two methods to your migrations: add_foreign_key and remove_foreign_key. Of course, you can also use these two methods to add or remove key in create_table and change_table.
Suppose we need to add a key that points from the comment table to the posts table. We can do this:
Class CreateComments
< ActiveRecord::Migration def change create_table :comments do |t| # … t.references :post # ... t.foreign_key :posts end # … end end 这些方法有一些额外的选项,例如 name,column,dependent。你可以参考文档。 也许有人会认为,准确的说这个 gem 并非只适用于 Rails 的新版本,不过它确实是只有 4.2 以上的版本才支持的(其实之前已经有第三方的支持了)。总之,我认为这个 gem 属于最有用的 gem 列表之一。 项目的 GitHub 链接 letter_opener 事实上,一个简单而有用的 gem,它是保存文件夹电子邮箱的一个插件而不是发送它们。通过激活这个 gem,你必须设置 letter_opener 作为应用配置中的递交方式(例如在 config/enviroments/development.rb之中) 太好啦!现在所有发出去的消息将被存贮在 /tmp/letter_opener 文件夹里,并且新的电子邮箱被发送之后会在浏览器中预览。它简单且实际。 请链接到Github。 Kaminari 该 gem 允许你很容易的创建任一复杂性的 paginators 模块。Kaminari 支持几个ORMs(ActiveRecord,Mongoid,MongoMapper)以及模板引擎(ERB,Haml,Slim)。 Kaminari 并不嵌套基础类:如 array,hash,Object 以及 ActiveRecord::Base。 让我们开始使用 Kaminari 吧,把它放在 gem 文件中,已经足够啦。某些功能变成可用之后,例如:页,每个以及对齐。现在,你可以借助于Kaminari.paginate_数组方法,来轻松地把你的 数组转换成一个分页模块,然后许多有用的分页功能将可以访问。 @paginatable_array = Kaminari.paginate_array(my_array_object).page(params[:page]).per(10) 默认的配置将被生成在 Kaminari· 配置初始化程序中。 default_per_page, max_per_page, max_pages – 这是一个简要的能被设置的选项列表。 除此之外,该分页的每个模块能被独立的配置。 class User < ActiveRecord::Base paginates_per 50 end 如果你需要定制 paginator,你可以通过运行一个生成器来创建模板: % rails g kaminari:views default # -e haml - if you want to use HAML template engine. 该模板将被创建于 app/views/kaminari/ 之中,现在,你可以轻松地编辑他们。 本地化(I18n)标签,主题和友好的 urls,以及其他有用的 gem 文档选项能被找到。 请链接到 Github CarrierWave 使用 CarrierWave 让你能够从你的 RoR 应用程序中上传任何文件。所有你需要做的事情如下: 创建一个 uploader: rails generate uploader ProductPhotoUploader 添加一些选项: 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 你已经可以使用 uploader 在存储器中保存文件了。 uploader = ProductPhotoUploader.new uploader.store!(my_file) CarrierWave 还允许你在临时存储、文件系统、甚至是云空间中储存文件。 你可以将 CarrierWave uploader 连接到 AR(还有其他 ORM 适配器)模型,并通过在数据库中保存一条记录来存储你的文件: 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'
In addition, you can change the quality of the uploaded image, clip it, encrypt the file, and do more while running, all of which can be found in the document.
Access the GitHub link for the project.
Urlify
A simple and easy-to-use gem for converting diacritic strings into ASCII-safe URI strings. After installing the gem, you can call the urlify function for anything, and it will immediately be converted to an equivalent compatible URI.
URLify.urlify ('Kj?le Test') # = > kjoele_test
Or:
URLify.urlify ('Kj?le Test',' -') # = > kjoele-test
Access the GitHub link for the project.
WickedPdf
WickedPdf is a RoR plug-in used to generate html into PDF. After adding this gem, you need to do the following steps:
Create initialization:
Rails generate wicked_pdf
Register for mine-type:
Mime::Type.register "application/pdf",: pdf
Considering that the gem uses wkhtmltopdf, you should specify its path in the settings of the gem.
WickedPdf.config = {exe_path:'/ usr/local/bin/wkhtmltopdf'}
Access the GitHub link for the project.
Countries
If you are faced with the task of dealing with information about different countries, this gem will provide you with all the data you need to solve the problem. It has the functions of searching by country name and region, currency information (symbols, codes), various forms of phone numbers, coordinates and so on. All of this requires you to create a country object (or get it from a global helper) after installing it, and then you can get the necessary information:
C = ISO3166::Country.new ('UA') # or to use global helper = Country [' UA'] c.name # = > "Ukraine" c. Alpha 2 cards = > "UK" c. Alpha 3 yards = > "UKR" c.longitude # = > "49 00 N" c.latitude # = > "32 00 E"
The following is the code on how to get currency information:
C.currency.code # = > "UAH" c.currency.symbol # = > "?" C.currency.name # = > "Hryvnia"
Or check whether the country is a member of the European Union:
C.in_eu? # = > false
The following is an example of searching for a country by name and currency code:
C = ISO3166::Country.find_country_by_name ('Ukraine')
C = ISO3166::Country.find_country_by_currency ('UAH')
Access the GitHub link for the project.
CanCanCan
This library allows you to easily configure permissions in RoR. With it, you can easily implement restrictions on access to specific resources. Its convenience is that the management of permissions is separate from the user, and all permissions are stored in a separate place. This is why you no longer have to do something repeatedly in controller, view, and database requests.
This library needs to define a current_user method in the controller. So you need to configure the authentication information first (this time I used Devise, but other gem can also do it). And then。 Then, generate an ability:
Rails g cancan:ability
Use the commands: read,: create,: update and: destroy to specify user permissions (the can/cannot method) (you can find more in the documentation).
Class Article::Ability include CanCan::Ability def initialize (user) case user when Admin cannot: manage,: profile can: read,: all when Moderator can: manage, [Apartment, RoomPrice], {lessor_id: user.id} can: manage, Photo, {photographer_id: user.id} can: manage, Lessor, {id: user.id} can: manage : profile end
After that, you can use can in the view? And cannot? Auxiliary method to check the permissions of the current user for a given action:
You can also use authorize! To authenticate the action in the controller:
Def show @ article = Article.find (params [: id]) authorize!: read, @ article end
Or you can also use the pre-filter load_and_authorize_resource, which loads resources and tries to authenticate them.
You can use the following ways to catch the exceptions thrown by CanCan::AccessDenied to handle errors related to permission authentication:
Class ApplicationController
< ActionController::Base rescue_from CanCan::AccessDenied do |exception| redirect_to root_url, :alert =>Exception.message end end
Additional information can be found in the documentation on GitHub.
Link to GitHub.
Formtastic
This gem provides great DSL support, which allows you to easily build a beautiful and intuitive semantic-based rich form, and it provides DSL that is easy to use: just list all the fields in a block of Semantic_form_for code and get a nice form:
"basic" do% > Advanced Options ",: id = >" advanced "do% >" URL Title ",: hint = >" Created automatically if left blank ",: required = > false% >: radio% >" Author "% > false% >: string,: label = >" Publication Date ",: required = > false% >
You can also use nested resources:
Nested form is also supported. You can use f.semantic_form_for (Rails style), but the Formtastic style is better, you can use the: for option.
: author,: name = > "Author"% >
You can easily change the behavior of input:
Class StringInput
< Formtastic::Inputs::StringInput def to_html puts "this is my modified version of StringInput" super end end 基于已有的input创建自己的input: class FlexibleTextInput < Formtastic::Inputs::StringInput def input_html_options super.merge(:class =>"flexible-text-area") end end
Or create an entirely new input type:
Class DatePickerInput include Formtastic::Inputs::Base def to_html #... End end
Mode of use:
: as = >: date_picker
Formtastic supports a considerable number 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 association, and many other features, as detailed in the documentation.
Project link for GitHub.
Capistrano
The tool allows commands to be executed through the concurrency of ssh on multiple remote machines. This gem is easy to use DSL. It enables you to define tasks that will be applied to certain role machines and to support tunnel connections through gateway machines.
After opening gem, you must execute:
Bundle exec cap install
Create a folder through configuration
If you are going to use a different environment, you must increase the STAGES parameter, for example: STAGES = local, sandbox, qa, production. Run a cap script and use this command-
Bundle exec cap [environments separated by gaps] [command] . For example, deploy a stage environment that looks like this:
Bundle exec cap staging deploy
Capistrano DSL is borrowed through Rake. Here is a simple example of this task:
Server 'example.com', roles: [: web,: app] server' example.org', roles: [: db,: workers] desc "Report Uptimes" task: uptime do on roles (: all) do | host | execute: any_command, "with args",: here, "and here" info "Host # {host} (# {host.roles.to_a.join (',')}): / t # {capture (: uptime)}" end end
Refer to all possible parameter documentation for more details on defining tasks, please connect to the plug-in and other things.
Link to Github.
After reading the above, do you have any further understanding of the 10 Ruby on Rails Gems provided for Web development? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.