Ten years ago, the WEB application framework, rails founder David Heinemeier Hansson, had recorded a video showing us how to create a blog engine in 15 minutes using Ruby on rails. This video successfully demonstrates the efficiency of Ruby on Rails writing WEB application core functionality through the design of Rails ' excellent MVC, custom superior Configuration (Convention over Configuration), and powerful code generation, scaffold, etc. Simple. Ruby on Rails This technology has also been a great shine in the Web 2.0 era and has become one of the best technology options for Web application development.
After 10 years of development, the software industry has already entered the era of cloud computing. Cloud storage, the cornerstone of cloud computing, has become an essential infrastructure for WEB development to cope with massive traffic and to control research and operation costs. Today, let's take a look at how to use Rails and seven cow cloud storage to create a picture-sharing social application prototype within 15 minutes.
Seven Neu Yun storage is a public cloud service that provides massive object storage capabilities, as well as cloud file processing and distribution services. Before we start, we need to create a seven-cow cloud storage trial account and learn some basics:
Seven Neu Yun storage is a key-value form of the object storage System, a Key corresponding to a resource (file).
A resource must be stored in a space (Bucket) and not exist separately. An account can create multiple spaces.
Create a basic Rails project
You should be able to use Ruby 1.9 above, rails 3.0 above any version, in this case we are using Ruby 2.2.3 and Rails 4.2.5.
After you have installed Ruby and rails, use the rails command to create the directory structure and basic files for your application Konata:
Copy Code code as follows:
While this command completes, we immediately get a blank Rails application that can run, execute the following commands, and access http://localhost:3000 in the browser to see how it works:
Copy Code code as follows:
Using Rails Scaffold to implement CRUD
We will use the scaffold feature of Rails to generate source code files such as model, controller, view, and database migration for working with picture Publishing.
Copy Code code as follows:
Rails Generate scaffold post title filename Qiniu_hash
Rake Db:migrate
The access http://localhost:3000/posts can see that we've got the full CRUD functionality of post, and just can't upload pictures yet.
Upload images using seven cow API
Modify Gemfile to include a reference to the seven bull Ruby SDK:
Copy Code code as follows:
Perform the following command to install the seven bull Ruby SDK. This should have been done to install bundle, but since the seven bull Ruby SDK relies on a mime-types version setting, the bundle Update command should be used to demote mime-types to resolve dependency conflicts.
Copy Code code as follows:
Edit Config/secrets.yml, where you add seven Neu Yun to store the account's key:
Copy Code code as follows:
Development
Secret_key_base: <YOUR_SECRET_KEY_BASE>
Qiniu_access_key: <YOUR_QINIU_ACCESS_KEY>
Qiniu_secret_key: <YOUR_QINIU_SECRET_KEY>
Create the CONFIG/INITIALIZERS/QINIU.RB and connect to the seven Neu Yun storage servers using the key you just added. The contents are as follows:
Require ' Qiniu '
qiniu.establish_connection! (
Access_key:Rails.application.secrets.qiniu_access_key,
secret_key:Rails.application.secrets.qiniu_secret_ Key
)
Attention:
AccessKey and Secretkey must be kept strictly confidential, not in the Web front-end source code that the user can view, or in the client binary code.
The seven-cow API provides a variety of uploading methods to meet the needs of different business scenarios. Here we choose to use the most representative, but also the simplest HTML form upload +http 303 Redirect to return the way to implement the client file directly upload seven Neu Yun storage. The advantage of this approach is that the client file does not need to be relayed through the Business Server (app server), which can optimize upload speed and reliability with the powerful CDN seven, and also save Business Server bandwidth.
Edit App/views/posts/_form.html.erb to upload the form according to the seven Neu Yun storage SDK constructs. Note The Upload voucher field, which we will create in Postscontroller:
<%= Form_tag ' http://upload.qiniu.com ', multipart:true do%> <%=
, @qiniu_upload_ Token%>
<div class= field > <%= label_tag:title%><br> <%=
' x: Title '%>
</div>
<div class= "field" >
<%= label_tag:image%><br>-
<%= File_field_tag:file%>
</div>
<div class= "Actions" >
<%= submit_tag ' Create '%>
</div>
<% End%>
Edit App/controllers/posts_controller.rb, add code to generate upload credentials, and create post instances based on the seven Neu Yun store custom response content:
def new
@qiniu_upload_token = Generate_qiniu_upload_token
@post = post.new
end
def create
upload _ret = Json.parse (base64.urlsafe_decode64 (Params[:upload_ret))
@post = post.new (
title:upload_ret[' title ') ],
filename:upload_ret[' fname '],
qiniu_hash:upload_ret[' hash ']
#
... End
Private
def generate_qiniu_upload_token
put_policy = Qiniu::auth::P utpolicy.new (' Konata ')
put_policy.return_body = {
fname: ' $ (fname) ',
Hash: ' $ (etag) ',
title: ' $ (x:title) '
}.to_ JSON
Put_policy.return_url = Create_posts_url
qiniu::auth.generate_uptoken (put_policy)
end
Edit Config/routes.rb to define the create action to use the Get method to also access:
:p OSTs do
collection does get
' create ', as:: "Create
end
"
Restart the rails server to access http://localhost:3000/posts/new, and now we can upload images to seven cattle cloud storage at the time of the new post.
Tips:
The file will be uploaded to the open space named Konata (bucket).
We do not specify key in code, and the seven Neu Yun store defaults to use the hash (ETag) value calculated based on the contents of the file as the key. This practice can be very simple to avoid the same content of the file storage more than a waste of space.
Since the upload form will be submitted directly to the seven Cow cloud storage server, our application backend can not get the title and other business object fields, we use the Seven Cow cloud storage API custom variables and custom response content features, through the seven Neu Yun storage upload API to get these fields.
Show pictures uploaded by users
Modify APP/HELPERS/APPLICATION_HELPER.RB, add Qiniu_image_url to facilitate the generation of picture URLs. To keep it simple, we directly hard-code the space domain name:
Def qiniu_image_url (post, format =: raw)
URL = "Http://7xokus.com2.z0.glb.qiniucdn.com/#{post.qiniu_hash}"
Case format
when:square
url << ' imageview2/1/w/300/h/300/q/90 ' when
:p review
url << '? Imageview2/2/w/1000/h/1000/q/90 '
when:raw
url << '? Attname=#{post.filename} '
else
URL End End
Modify App/views/posts/index.html.erb and App/views/posts/show.html.erb to invoke the URL helper display image you just created:
<tr>
<td><%= post.title%></td>
<td><%= link_to Image_tag (qiniu_image_url (Post,: square), size: '%></td> ', post
<td><%= link_to ' Destroy ', post, Method::d elete, data: {Confirm: ' Are you sure '}%></td>
</tr>
<p>
<%= link_to image_tag (Qiniu_image_url (@post,:p Review)), Qiniu_image_url (@post), class: ' Image '% >
</p>
<%= link_to ' back ', Posts_path%>
Modify CONFIG/ROUTES.RB to set the site root directory to the Posts List page:
Root ' Posts#index '
Visit http://localhost:3000 and now we can see the pictures just uploaded.
Tips:
resources within each space (bucket) can be accessed through the space's default or custom domain name, plus the HTTP URL constructed by the file key.
You can add a specific query parameter after the URL, call seven Neu Yun store a powerful data processing (FOP) API, and generate a custom format thumbnail in real time.
You can specify the name of the file to use when downloading the URL through the query parameter AttName.
Simple UI Landscaping
Modify the App/views/posts/index.html.erb to change the original table layout to Flexbox layout:
<div class= "Posts" >
<% @posts. Each do |post|%>
<p>
<%= link_to Image_tag (qiniu_ Image_url (post,: square), size: ' A ', Post, class: ' Image '%>
<br>
<%= post.title%>
< br>
<%= link_to ' Destroy ', post, Method::d elete, data: {confirm: ' Are you sure? '}%>
</p>
&L t;% End%>
</div>
Modify the App/assets/stylesheets/application.css and add the corresponding CSS:
body {
padding:20px;
}
a.image:hover {
background-color:transparent;
}
div.posts {
Display:flex;
Flex-flow:row Wrap;
Justify-content:space-between;
}
To access http://localhost:3000, the picture list looks like a normal photo album.
Add user account Features
There are two obvious problems with our application: No one is sharing the picture, and anyone can delete the post. This is obviously an unacceptable problem for a social application. This is obviously unacceptable for a social application, so next we will use the devise components that are popular with the Rails community to directly obtain user registration, login, validation subsystem, and the ability to record the image publisher information.
Modify Gemfile to add dependency on devise:
Copy Code code as follows:
Perform the following command to install devise, generate User model, and the data migration we need:
Copy Code code as follows:
Bundle
Rails Generate Devise:install
Rails Generate devise user
Rails Generate migration Add_author_to_posts creator:belongs_to
Rake Db:migrate
Modify APP/CONTROLLERS/POSTS_CONTROLLER.RB, log in for operations other than view, and record the identity of the publisher when Post is published:
before_action:authenticate_user!, except: [: Index,: show]
def create
#
... @post = post.new (
title:upload_ret[' title '),
filename:upload_ret[' fname ',
qiniu_hash:upload_ret[' Hash '],
creator:current_user
)
#
... End
Modify APP/MODELS/POST.RB to add a subordinate association with USER model:
Copy Code code as follows:
Belongs_to:creator, class_name: ' User '
Modify App/views/layouts/application.html.erb, add login status information and logout link:
Modify App/views/posts/index.html.erb to restrict post Publisher to delete this post:
<% if user_signed_in? and post.creator = = Current_User%>
<br>
<%= link_to ' Destroy ', post, Method::d elete, data: {Confirm : ' Are you sure? '} %>
<% End%>
After restarting Rails server, access to http://localhost:3000, now users need to register to log in order to publish pictures.
Realize the point of praise function
Finally, as a social application, there is no point of praise function How to let the point of praise Crazy Demon satisfied?! We will add a like scaffold to handle the point Zane storage point of praise information.
Execute the following command to generate Scaffold,like model as a join model and subordinate to both Post and User:
Copy Code code as follows:
Rails Generate scaffold like post:belongs_to user:belongs_to
Rake Db:migrate
Modify APP/MODELS/POST.RB to establish a "owning/nesting" relationship between post and like model:
Copy Code code as follows:
modifying app/models/like.rb, restricting a point to a post can only be ordered once by the praise:
Copy Code code as follows:
Validates_uniqueness_of:user, scope::p OST
Modify CONFIG/ROUTES.RB to set likes as a nested resource for posts:
Copy Code code as follows:
OSTs:p
# ...
Resources:likes
End
Modify App/views/posts/index.html.erb, add dot-hop information display and AJAX Point-praise Links:
<%= post.title%>
<br>
<%= content_tag (: Span, "#{post.likes.count} likes", ID: "Post_#{post.id }_likes ")%>
<% if user_signed_in?%>
<br>
<%= link_to ' like ', Post_likes_path (POST), Method::p ost, Remote:true%>
<% if post.creator = = Current_User%> <%= link_to
' Destroy ', post, meth OD::d elete, data: {confirm: ' Are you sure? '}%> <% end%> <% end%>
Modify APP/CONTROLLERS/LIKES_CONTROLLER.RB to truly likes resources into posts nesting resources and record the identity of the awesome Monster at the point of praise:
Before_action:set_post
def create
@like = @post. Likes.new (user:current_user)
respond_to do |format|< C14/>if @like. Save
Format.js {}
else
format.js {} End-end
private
def Set_post
@post = Post.find (params[:p ost_id])
end
Create App/views/likes/create.js.erb, and use server-generated JavaScript to update the point-praise message:
Copy Code code as follows:
$ ("#<%=" post_#{@post. Id}_likes "%>"). Text ("<%=" #{@post. Likes.count} likes "%>")
After restarting Rails server, visit http://localhost:3000, let's have a nice place.
Summary
Although this is only a simple prototype, but because the use of seven cattle cloud storage as a picture storage backend, our social applications in the initial phase of the prototype has the ability to provide high-speed, reliable service to the potential of large-scale users.
Briefly review what we have just learned. With the Rails code generation feature, scaffold for business object maintenance based on the CRUD structure, and business operations are highly efficient, and using seven-cow cloud storage can easily handle file storage in the business system, get the cloud processing capability of multimedia files such as Picture videos, reduce Even avoid some of the research and Development and operation of the maintenance work. I hope this video will help you to understand these two excellent development tools, intuitive to feel their efficient and powerful and easy-to-use.
Resources
Ruby on Rails Guides
Seven Cattle Developer Center
Sample code
Https://github.com/rainux/konata-sample
Instead of directly experimenting with sample code, you should write the code yourself and write the code yourself to help deepen your understanding and memory.