GoRails

1.Environment Variables<b>[finish]</b>
2.Ruby Version Managers<b>[finish]</b>
3.Rails Application Structure<b>[finish]</b>
4.The Params Hash<b>[finish]</b>
5.Sending Data Between Controllers And Views<b>[finish]</b>
6.Querying Named Scopes Across Models with ActiveRecord::Relation#merge<b>[finish]</b>
7.Styling with Bootstrap Sass <b>[finish]</b>
8.Debugging With BetterErrors<b>[finish]</b>
9.Pretty urls with FriendlyID<b>[finish]</b>
10.Pagination with will_paginate<b>[finish]</b>
11.File Uploading with Carrierwave<b>[finish]</b>
12.User Authentication with Devise<b>[finish]</b>
13.Keeping track with Annotate<b>[finish]</b>
14.Sending emails with Mandrill
15.Understanding Semantic Versioning<b>[finish]</b>
16.Button Loading Animations with jQuery UJS<b>[finish]</b>
17.jQuery UJS and AJAX<b>[finish]</b>
18.jQuery UJS Callbacks
19.A Look Into Routing<b>[finish]</b>
20.Authorization With CanCanCan
21.Rails 4.2 Introduction <b>[finish]</b>
22.Authorization with Pundit
23.Consuming an API Using HTTParty and Creating a Gem<b>[finish]</b>
24.Liking Posts
25.Forum Series Part 1: Architecture<b>[finish]</b>
26.Forum Series Part 2: Routes<b>[finish]</b>
27.Forum Series Part 3: Nested Attributes and fields_for<b>[finish]</b>
28.Forum Series Part 4: div_for
29.Forum Series Part 5: Email Notifications with Rails 4.2, deliver_later, and Previews
30.Forum Series Part 6: Search with Ransack
31.Forum Series Part 7: Time Zones using the local_time Gem
32.Markdown and Emoji with the html-pipeline gem
33.Sign In With Twitter using Omniauth and the Twitter gem<b>[finish]</b>
34.Forms With Multiple Submit Buttons
35.API Tokens with Devise Token Authenticatable
36.Comments With Polymorphic Associations
37.File Uploads with Refile
38.Upload Progress with Refile Javascript
39.Refactoring Controller Methods
40.Fragment Caching And oEmbed
41.Soft Delete with Paranoia<b>[finish]</b>
42.Concerns: Making a Soft Deletable module
43.Introduction to Importing from CSV
44.CSV Upload Form to Import Records
45.Exporting Records To CSV
46.Refactoring CSV Uploads with ActiveModel::Model
47.Multitenancy with the Apartment gem
48.Handling Subdomains and Multitenancy From Scratch
49.Newsletter Sign Up Form with country_select
50.Using Ruby Service Objects To Refactor Your Rails Code
51.PDF Receipts
52.Refactoring with the Null Object Pattern
53.How To Setup Vagrant For Rails Development<b>[finish]</b>
54.Debugging Performance Problems In Your Views
55.My Development Environment
56.Refactoring Your jQuery Code with Objects in Coffeescript
57.Including Javascript and CSS Libraries With Rails
58.Clean Javascript Code Using Data-Behavior On The Frontend
59.How To Create A Gem For Frontend Javascript And CSS Libraries
60.Basic Authentication and RSS Feeds
61.Manage Assets With Rails Assets<b>[finish]</b>
62.Open Source Vlog - Where Do We Even Start?
63.Open Source Vlog - Housekeeping and Merging Pull Requests
64.Open Source Vlog - Setting Up Rspec
65.Open Source Vlog - Setting Up For The Future
66.Open Source Vlog - Just Deleting Things
67.Open Source Vlog - Building A Calendar From Scratch
68.Open Source Vlog - Refactoring Our Calendar
69.Open Source Vlog - Filtering Events
70.Activity Feed From Scratch
71.Pair Programming on Rails Scopes
72.Open Source Vlog - Finding a balance between Ruby and ERB
73.Open Source Vlog - Simple And Clean RubyGem With Rails Engines
74.Elegant Refactoring for Week and Month Calendars
75.Rails 5's ActionCable and Websockets Introduction
76.Open Source Vlog - Refactoring Events And Uploading Version 2.0
77.Open Source Vlog - Rails Generators
78.@Mentions, Autocomplete, Notifications, and Links
79.Open Source Vlog - Sorting Calendar Events
80.Redirect To Current Page After Login
81.Open Source Vlog - Writing Rspec Tests
82.Usability And Video Autoplay With Wistia
83.Using Purchased Themes with Rails
84.What Is A State Machine? <b>[finish]</b>
85.The State_Machine Gem<b>[finish]</b>
86.Scheduling Posts
87.Scheduled Cron Jobs with the Whenever Gem
88.Using Bootstrap 4 Rubygem with Rails<b>[finish]</b>
89.Advanced Search, Autocomplete and Suggestions with ElasticSearch and the Searckick gem
90.Subscriptions with Stripe
91.Adding Stripe update card form, Cancel, and Resubscribe
92.Contributing To Open Source: Fixing A Bug In Devise
93.Using Webhooks with Stripe
94.Admin Interfaces with Administrate
95.Background Workers with ActiveJob and Sidekiq
96.In-App Navbar Notifications
97.Integrating Braintree (and PayPal)
98.Virtual Attributes And Rails 5 Attribute API
99.Metaprogramming Virtual Attributes
100.Sharing Data With Javascript
101.ShareMeow
102.Deploying To Production on Heroku with Puma
103.How to Deploy ActionCable and Rails 5 To Production
104.Deploying Sidekiq To Heroku
105.In-App Messages Between Users
106.Mitigating Spammers with Recaptcha
107.How to Upgrade to Turbolinks 5
108.Advanced Messaging with Mailboxer: Mark As Read
109.Advanced Mailboxer: Multiple User Conversations
110.Advanced Messaging with Mailboxer: Adding Attachments
111.Memoization
112.Upgrading simple_calendar for Rails 5
113.GoRails Performance - The Techniques I Use
114.Russian Doll Caching with Rails 5
115.Advanced Caching with User Permissions and Authorization
116.Turbolinks 5 Forms for Mobile
117.Sentiment Analysis with the Sentimental Gem
118.Repost / Retweet / Reblog
119.Improving Query Performance with Database Indexes
120.Inviting Users with devise_invitable
121.Custom will_paginate Methods
122.Message Templates
123.Wrapping Business Logic with Plain Old Ruby Objects
124.Improving In-App Notifications
125.Realtime Notifications with ActionCable
126.How ActionCable Uses Redis
127.Solving FizzBuzz in Ruby
128.Disabling ActionCable for Unauthenticated Users
129.Group Chat with ActionCable: Part 1
130.Group Chat with ActionCable: Part 2
131.Group Chat with ActionCable: Part 3
132.Group Chat with ActionCable: Part 4
133.Group Chat with ActionCable: Part 5
134.Sending Emails with SMTP and Sendgrid
135.Group Chat with ActionCable: Part 6
136.Group Chat with ActionCable: Part 7
137.Multi-User Spreadsheets with ActionCable: Part 1
138.Multi-User Spreadsheets with ActionCable: Part 2
139.Multi-User Spreadsheets with ActionCable: Part 3
140.Multi-User Spreadsheets with ActionCable: Part 4
141.Multi-User Spreadsheets with ActionCable: Part 5
142.File Uploads in Rails With Shrine
143.Direct Messages in Realtime with ActionCable
144.Direct File Uploads to S3: Part 1
145.Direct File Uploads to S3: Part 2
146.Direct File Uploads to S3: Part 3
147.Electronic Signatures with the Docusign API
148.Receiving Webhooks in Development with Ngrok and Docusign
149.Protecting from XSS with Sanitize

1.Environment Variables

一个常见的场景是要隐藏数据库密码的变量,下面解决几种方式:
其中数据库密码的格式应该如下所示:

#database.yml
password: <%= ENV["PASSWORD"]%> #必须是erb的形式,源码是通过erb进行解析的

1、临时性的解决方法

#PASSWORD=password rails c
上面的方法只是对本次启动有效,属于临时性解决方案

2、将环境变量存在本地

#ubuntu
ubuntu启动bash的过程中,会启动~/.bash_profile文件,可以在文件中输入如下代码:
export PASSWORD=root  #.bash_profile文件需要重启或者当下执行source .bash_profile才能生效

#mac
mac已经安装了zsh,不会自动触发.bash_profile文件,可以在.zshrc文件添加如下代码:
source .bash_profile

测试如上的代码是否成功,可以通过终端执行env代码查看

3、在开发环境中可以通过dotenv

1、gem 'dotenv-rails'
2、项目文件中(第一层级)建立.env文件,按照类似如下格式填写
S3_BUCKET=YOURS3BUCKET

参考视频
4、在生产环境中使用Figaro
参考视频

2.Ruby Version Managers

该视频讲述了ruby的版本管理工具,包括rvm和rbenv,但是目前对目前rvm如何管理各种gem或者说各种版本的rails如何操作不清楚。

3.Rails Application Structure

这个视频只是介绍rails的结构,但是在行文中经常出现如下的代码

require ::File.expand_path('../config/environment', __FILE__)

下面分别对expand_path和require方法进行解释和理解。

expand_path的解释和理解:
expand_path是将路径名转变为绝对路径名,下面介绍几种类型

#1.出现用户目录“~”,扩展用户目录成为绝对路径
File.expand_path("~oracle/bin") #=> "/home/oracle/bin"

#2.出现文件名和路径名称,将两者结合
File.expand_path("ruby", "/usr/bin") #=> "/usr/bin/ruby"

#3.更为常见的是这种形式,出现__FILE__,其中这个变量的意为所处文件的文件名,下面代码中:
File.expand_path("../../lib/mygem.rb", __FILE__)
#=> ".../path/to/project/lib/mygem.rb"
其中__FILE__表示为mygem.rb,该文件的父目录为project,父目录的父目录为to,该to文件夹的绝对目录为.../path/,进行补全操作,示例所示。

require的用法和理解,并且对比require_relative,load,include,extend。
按照api的解释,require的文件名应该是绝对路径,按照上面的出现的所示,其中“::”表示回到root路径中,如果require的是相对路径,那么require的文件需要到$LOAD_PATH(又名$:)中寻找,方式如下:

irb:$LOAD_PATH

["/Users/jayzen/.rvm/gems/ruby-2.3.0@global/gems/did_you_mean-1.0.0/lib", "/Users/jayzen/.rvm/rubies/ruby-2.3.0/lib/ruby/site_ruby/2.3.0", "/Users/jayzen/.rvm/rubies/ruby-2.3.0/lib/ruby/site_ruby/2.3.0/x86_64-darwin15", "/Users/jayzen/.rvm/rubies/ruby-2.3.0/lib/ruby/site_ruby", "/Users/jayzen/.rvm/rubies/ruby-2.3.0/lib/ruby/vendor_ruby/2.3.0", "/Users/jayzen/.rvm/rubies/ruby-2.3.0/lib/ruby/vendor_ruby/2.3.0/x86_64-darwin15", "/Users/jayzen/.rvm/rubies/ruby-2.3.0/lib/ruby/vendor_ruby", "/Users/jayzen/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0", "/Users/jayzen/.rvm/rubies/ruby-2.3.0/lib/ruby/2.3.0/x86_64-darwin15"]

但是目前的ruby版本中已经将当前路径从$LOAD_PATH中删除了,因此下面的方式是会出来LoadError错误的:

#demo.rb
require  "test" #test.rb和demo.rb处于同一个文件件中

如果要采取加载同一个文件夹中的路径,需要使用如下的代码:

#demo.rb
require "./test"
require_relative "test"

load和require的区别如下:

1. 使用require文件的时候可以不使用后缀,load需要
2. require只会加载一次,第一次成功加载,返回true,第二次加载,返回false
3. load可以进行反复多次加载

对比include,extend与require和load的区别:

1. include和extend与require,load的区别在于,前两者其实在同一个文件中引入模名,后两者是在不同的文件中引入文件名。
2. 类中include模块是引入模块中的实例方法作为类的实例方法使用,类中extend模块是引入模块中的实例方法作为类的类方法使用。
4.The Params Hash

视频讲述了生成params值的三种方式,guides中都有讲述,这边做一个小结。

#通过url
http://localhost:3000/posts?page=2  #params[:page]=2

#通过设置routes
get "blog/:id", to: "blog#show"  #params[:id]=2

#通过view中的form_tag和form_for
其中form_tag,直接获取属性的值,而form_for获得一个嵌套参数
5.Sending Data Between Controllers And Views

开发的过程中,一个显著的现象是controller中的实例变量才能被传递到对应的view中,而局部变量则不能被传递,如何解释这种现象,视频中的材料因为暂时没有找到对应的源码解读,因此在这里自己做一些理解和整理。
在元编程中,对象是一组实例变量和一个指向类的引用组成的。具体的实例代码如下:

class Demo
  def test
    @test = "this is the test method in class demo"
  end
end

obj = Demo.new
obj.test #只有方法被调用,实例变量@test才能出现在实例obj中
puts obj.instance_variables #=>[:@test]

因此我自己的理解是,对于controller的action所render的对象是一个controller的实例化对象,对象能够访问对象内部的实例变量,而对于局部变量,出了局部作用域,该变量就无效了。

6.Querying Named Scopes Across Models with ActiveRecord::Relation#merge

这边介绍集中ActiveRecord的一些查询方法,指出joins和left_joins(left_outer_joins)的区别。

#存在两个model,分别是user和post,其中user has many posts
User.joins(:posts) #必须满足下面语句中的on条件,才能够返回结果
# SELECT "users".*
# FROM "users"
# INNER JOIN "posts" ON "posts"."user_id" = "users"."id"

User.left_joins(:posts) #如果右边没有满足条件的实例,会返回全部左边的实例
User.left_outer_joins(:posts) #和上面的效果是一致的
# SELECT "users".*
# FROM "users"
# INNER JOIN "posts" ON "posts"."user_id" = "users"."id"

本视频主要讲述,在model中的scope过程中,merge方法有利于简化model的查询语句。语句代码如下:

#author.rb
class Author < ActiveRecord::Base
  has_many :books
end

#book
class Book < ActiveRecord::Base
  belongs_to :author
  scope :available, ->{ where(available: true) }
end

#没有merge情况下:
Author.joins(:books).where("books.available = ?", true) #成功
Author.joins(:books).available #报错,因为available是Book类的方法

#存在merge的情况下:
Author.joins(:books).merge(Book.available) #成功,和上面的效果一致,而且表现的简洁

#SQL语法如下所示
SELECT "authors".* FROM "authors" INNER JOIN "books" ON "books"."author_id" = "authors"."id" WHERE "books"."available" = 't'
7.Styling with Bootstrap Sass

在自己笔记的协同环境和相关配置中有介绍。

8.Debugging With BetterErrors

改变默认的出错页面,并且可以在页面上进行debug,注意必须在development而不是在production中,因此gem的安装必须按照如下所示形式:

#gemfile
group :development do 
  gem "better_errors"
  gem 'binding_of_caller'
end
9.Pretty urls with FriendlyID

相关的内容已经在railscasts中进行了说明,视频中的不足在于对于history也没有进行操作,自己针对history的内容没有执行成功。

10.Pagination with will_paginate

已经在railscasts总结中给出详细描述。

11.File Uploading with Carrierwave

关于使用Carrierwave来进行文件上传的已经在railscasts总结中给出。这里使用rails自带的方法来上传附件。

#模型
rails g scaffold book name cover_filename

#model数据呈现
class Book < ApplicationRecord
  attr_accessor :cover

  after_save :save_cover_image, if: :cover

  def save_cover_image
    filename = cover.original_filename
    folder   = "public/books/#{id}/cover"

    FileUtils.mkdir_p folder

    f = File.open File.join(folder, filename), "wb"
    f.write cover.read()
    f.close

    self.cover = nil
    update cover_filename: filename
  end
end

#view数据呈现
#_form.html.erb
<%= f.file_field :cover %>

#show.html.erb
<%= image_tag "/books/#{@book.id}/cover/#
12.User Authentication with Devise

在ruby on rails tutorial中有成套的建立用户登录的机制,但是如果写出来的会很话时间,这里可以使用devise这个gem作为用户的验证,这里记住一个是:
1、假定model是user的情况下,熟悉devise的一些基本路由和由此设定的方法。
2、假定user要发布一篇文章post,user和post需要进行关联,熟悉关联过程中的一些filter方法。
3、在最开始使用devise过程中的基本设置方法。
下面的代码基本上是基于如上的一些设置展开的。

#安装devise
gem 'devise' #gemfile中添加devise
rails g devise:install #终端中输入代码显示安装devise,会出现上面的提示
rails g devise:views #会显示出登录界面,默认有界面,但是只有执行这段代码才能找到修改界面
rails g devise user #使用user作为devise的model

#前端提示显示
<p class="notice"><%= notice %><p>
<p class="alert"><%= alert %></p>

在上面的基础上执行rails routes

                  Prefix Verb   URI Pattern                    Controller#Action
        new_user_session GET    /users/sign_in(.:format)       devise/sessions#new
            user_session POST   /users/sign_in(.:format)       devise/sessions#create
    destroy_user_session DELETE /users/sign_out(.:format)      devise/sessions#destroy
           user_password POST   /users/password(.:format)      devise/passwords#create
       new_user_password GET    /users/password/new(.:format)  devise/passwords#new
      edit_user_password GET    /users/password/edit(.:format) devise/passwords#edit
                         PATCH  /users/password(.:format)      devise/passwords#update
                         PUT    /users/password(.:format)      devise/passwords#update
cancel_user_registration GET    /users/cancel(.:format)        devise/registrations#cancel
       user_registration POST   /users(.:format)               devise/registrations#create
   new_user_registration GET    /users/sign_up(.:format)       devise/registrations#new
  edit_user_registration GET    /users/edit(.:format)          devise/registrations#edit
                         PATCH  /users(.:format)               devise/registrations#update
                         PUT    /users(.:format)               devise/registrations#update
                         DELETE /users(.:format)               devise/registrations#destroy

因此可以使用下面的方法放在view或者controller中

new_user_registration_path #用户注册url
new_user_session_path #用户登录url
destroy_user_session_path #用户退出url
edit_user_registration_path #对登录的用户进行编辑

user_signed_in? #判断用户是否登录
current_user #当前用户

authenticate_user! #在controller中的before_action中的过滤方法,在关联的模型的controller中使用

在model中建立如下devide(user)扩展了如下的模块:

class User < ApplicationRecord
 # Include default devise modules. Others available are:
 # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable
end
#比如在博客中,如果不需要注册,需要将:registerable模块取消
#建立博客的原始用户方式是在终端中输入如下的片段
#rails c 
User.create(email: "xx", password: "111111")

根据是否通过验证来显示不同的主界面

root "welcome#index"

authenticated :user do
  root "users#index"
end
13.Keeping track with Annotate

使用annotate可以在model或者routes.rb中看到具体的schema或者路径展开。但是在rails中其实可以通过db/schema.rb和通过rails routes看到具体的模式。

gem 'annotate' #安装
annotate  #执行 
14.Sending emails with Mandrill

根据视频提醒,这个应用已经开始付费,暂时不看这个视频,相关的应用也有Sendgrid, Postmark, MailJet, MailGun,遇到具体的项目再说,另外rails guides中用rails自带的邮件发送也是可以的。

15.Understanding Semantic Versioning

主要是讲了版本号的各种意义,参考

x.y.z(for instance ruby 2.3.1)
主版本号:当你做了不兼容的 API 修改,
次版本号:当你做了向下兼容的功能性新增,
修订号:当你做了向下兼容的问题修正。
16.Button Loading Animations with jQuery UJS

该episode是介绍font awesome的一些图标,这些图标已经被内建为jquery的样式,在rails的程序中默认已经内建。

//= require jquery
//= require jquery_ujs

使用方式如下,当表单提交不成功的时候会出现一种中间状态,下面是rails默认提交表单和simpleform表单的使用方式:

#默认形式,使用scaffold的形式是f.submit,需要更改为f.
<%= f.button "Sign In", class: "btn btn-success", data: {disable_with: "<i class='fa fa-spinner fa-spin'></i> Signing in..."} %>

#simpleform形式
<%= f.button :button, "Save Post".html_safe, data: {disable_with: "<i class='fa fa-spinner fa-spin'></i> Saving..."} %>
17.jQuery UJS and AJAX

rails内建了jquery,jquery支持ajax操作,该episode通过实例介绍了通过ajax操作项目。项目说明,post这个model有一个published_at字段,通过publish链接,点击无刷新页面更新这个字段的值,下面介绍相关的步骤:

#post具有published_at这个日期字段
#设置routes.rb,其中rails routes #=>publish_post_path
resources :posts do
  member do
    patch :publish
  end
end

#设置PostsController.rb文件
def publish
  @post.update(published_at: Time.zone.now)
end

#设置view文件,出现remote: true的值时,会自动寻找publish.js.erb文件
<span id="published_at"><%= @post.published_at %></span>
<%= link_to "publish", publish_post_path(@post), method: :patch, remote: true %>

#添加js文件publish.js.erb文件
$("#published_at").text("<%= @post.published_at %>")
19.A Look Into Routing

介绍routes的内容,详细的内容guides中已经做了介绍,这边着重介绍了scope,member,collection。

21.Rails 4.2 Introduction

介绍了rails4.2的两个新功能,分别是active job和web console,其中web console是在网页出现错误的情况下网页界面出现调试界面,类似于BetterErrors这个gem。

23.Consuming an API Using HTTParty and Creating a Gem

这个视频通过HTTParty这个gem来获取相关api的内容,其中在页面端获取api的信息,可以通过安装一个chrome的插件JSONView,这个插件可以通过下面的方式更好的呈现json内容:

http://localhost:3000/users/1.json

另外一个内容是通过bundle命令来生成一个gem,使用的系统是animatedgif.me

获取上面网站的api可以通过如下方式:

#每次刷新,内容都是不同的
http://animatedgif.me/cat.json

下面介绍创建一个gem并且使用httparty这个gem

#使用bundle建立gem的命令行
bundle gem animated_demo

#animated_demo.gemspec中添加httparty以及修改spec.homepage
spec.homepage      = ""  #必须修改,不然会报错
spec.add_dependency 'httparty', '~> 0.14.0'

#修改内容lib/animated_demo.rb
require "bundler/setup"  #必须添加,不然irb会报错
require "animated_demo/version"
require "httparty"

module AnimatedDemo
  include HTTParty

  base_uri "animatedgif.me" #添加url

  def self.find(id)
    retrieve_url get("/gifs/#{id}.json")
  end

  def self.tagged(tag)
    retrieve_url get("/#{tag}.json")

  end

  def self.random(tag)
    tagged(tag)
  end

  private
    def self.retrieve_url(response)
      response.parsed_response["url"]
    end
end

#irb进行操作和测试
require_relative 'lib/animated_demo'  #必须在animated_demo.rb添加require "bundler/setup"
#上面的值放回true
AnimatedDemo #返回AnimatedDemo
AnimatedDemo.find(10) #测试成功

#上传到github中,如果是在rails程序引用,需要要程序中使用下列语句
gem 'animated_demo', git: 'https://github.com/Jayzen/animated_demo.git'







25.Forum Series Part 1: Architecture

这个章节主要说明项目的数据库结构以及需要安装的gem文件:
source code url

#数据库文件
User - Devise

email:string
password:string
has_many :forum_threads has_many :forum_posts

ForumThread

user_id:integer
subject:string
belongs_to :user has_many :forum_posts

ForumPost

forum_thread_id:integer
user_id:interger
body:text
belongs_to :forum_thread belongs_to :user

#gemfile文件
group :development do
  gem "annotate"
  gem "better_errors"
  gem "binding_of_caller"
end

gem "devise"

#安装语句
rails g annotate:install
rails g devise:install
rails g devise:views
rails g devise User

rails g model ForumThread user_id:integer subject:string
rails g model ForumPost user_id:integer forum_thread_id:integer body:text
26.Forum Series Part 2: Routes

这个episode主要讲述的是routes的用法,这里用到了嵌套路由,railsguides中已经做了比较详细的介绍,具体代码如下所示:

resources :forum_threads do
  resources :forum_posts, module: :forum_threads
end

这里module的作用是应用的目录结构中体现路由关系,需要在controller文件夹中放置form_threads文件夹,其中放置forum_posts_controller.rb文件,在views文件夹中放置forum_threads文件夹。

27.Forum Series Part 3: Nested Attributes and fields_for

内容已经在guides的view的第三节已经有介绍,而且考虑的已经比较全面。需要注意的是rails5中的belongs_to的关联,必须关联对象已经存在的情况下才能保存,为了避免这个问题,需要进行如下的设置:

belongs_to :post, optional: true
33.Sign In With Twitter using Omniauth and the Twitter gem

该视频的主题如标题内容所示,使用的gem是omniauth-twitter这个gem,不需要添加其他的gem,思路主要是通过在本地的系统中建立一个user模型,分别与omniauth-twitter提供的字段对应进行存储。
需要到twitter的官网进行设置,地址,其中callback url的地址需要为:

http://127.0.0.1:3000/auth/twitter/callback

记录api key和api secret的值,并且改变相应的permissions权限。上面的key和secret的记录方式为:

#config/secrets.rb
development:
  twitter_api_key: DRZKK44rHuZt13Rp4dc2Babnr
  twitter_api_secret: 7Rw5U0QzeXNmR6heCrLpgLfu4Bvr5Dcfi7PJJFIA4fMMddTBOM

#config/initializer/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
  provider :twitter, Rails.application.secrets.twitter_api_key, Rails.application.secrets.twitter_api_secret
end

#gemfile
gem 'omniauth-twitter'

下面的代码为全部

#使用的twitter的链接地址为
#http://127.0.0.1:3000/auth/twitter

#设置相应的routes.rb
resources :twitters
root 'twitters#index'
get '/auth/:provider/callback', to: "sessions#create"

#建立相应的model
rails g model user provider uid name token secret profile_image

#user.rb
class User < ApplicationRecord
  def self.find_or_create_from_auth_hash(auth_hash)
    user = where(provider: auth_hash.provider, uid: auth_hash.uid).first_or_create
    user.update(
      name: auth_hash.info.name,
      profile_image: auth_hash.info.image,
      token: auth_hash.credentials.token,
      secret: auth_hash.credentials.secret
    )
    user
  end
end

#sessions_controller.rb
class SessionsController < ApplicationController
  def create
    #rails :test   #可以使用左边这种方式进行debug,输入auth_hash查看全部的值
    @user = User.find_or_create_from_auth_hash(auth_hash)
    session[:user_id] = @user.id
    redirect_to root_path
  end

  protected
    def auth_hash
      request.env['omniauth.auth']
    end
end

#application_controller.rb
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  def current_user
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end
  helper_method :current_user #helper方法可以在view中被使用,不然在controller中无效
end

#layouts/application.html.erb
<% if current_user %>
  <%= current_user.name %>
<% end %>

该episode中还讲述了在项目中发布twitter的用法,但是基本上没有用到,项目需求过程中再说。

41.Soft Delete with Paranoia

gitbook中已经有总结

53.How To Setup Vagrant For Rails Development

该视频是用vagrant来提供在不同的本地环境中部署和开发rails项目,同时使用了chef的自动化部署(这个是不熟悉的,以后需要掌握)。本视频文档地址

61.Manage Assets With Rails Assets

使用rails assets来管理assets,rails默认使用assets pipeline来管理assets,这个episode的初衷以及益处是什么需要再深入理解assets pipeline的时候再做分析。rails assets的地址和使用方式如下:

#以使用bootstrap为例

#gemfile文件
source 'https://rails-assets.org' do
  gem 'rails-assets-bootstrap'
end

#application.js文件
//= require bootstrap

#application.css文件
/* 
*= require_self
 *= require bootstrap
 *= require_tree
*/
84.What Is A State Machine?

解释什么是STM(finite state machine),用wiki的解释为:是表示有限个状态以及在这些状态之间的转移和动作等行为的数学模型。

85.The State_Machine Gem

介绍state_machine这个gem,看的不是很明白,不过应该是在进行交易的时候使用,介绍交易过程中出现的各种状态,功能是为需求而生的,下次遇到具体项目的时候再回过头来看STM。

88.Using Bootstrap 4 Rubygem with Rails

使用BT4
github中的bt4使用帮助

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,117评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,328评论 1 293
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,839评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,007评论 0 206
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,384评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,629评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,880评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,593评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,313评论 1 243
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,575评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,066评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,392评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,052评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,082评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,844评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,662评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,575评论 2 270

推荐阅读更多精彩内容