git初始代码https://github.com/chentianwei411/at-mentions-with-action-text
首先,开分支onboardingbar.
然后,
rails g scaffold Team user:references name
rails g migration AddTwitterToUsers twitter
rails db:migrate
在user.rb上添加
has_many :teams
在_navbar.html.erb上添加导航链接:
在用户注册app/views/devise/registrations/edit.html.erb上添加twitter field:
在application_controller.rb上添加参数白名单:
protecteddef configure_permitted_parametersdevise_parameter_sanitizer.permit(:sign_up, keys: [:name])devise_parameter_sanitizer.permit(:account_update, keys: [:name, :twitter])end
添加OnboardingBar:
在app/views/home/index.html.erb
<% if user_signed_in? %>
<% end %>
下一步&#xff0c;user.rb添加方法来判断onboardingbar的进度&#xff1a;
def onboarding_percentsteps &#61; [:twitter?, :has_team?]conplete &#61; steps.select{ |step| send(step)}complete.length / steps.length.to_f * 100enddef has_team?teams.any?end# select()方法&#xff0c;筛选返回值为true的数组项
# Ruby#send()方法&#xff0c;可以使用symbol符号方法
# 方法最后返回的值的计算必须使用浮点格式&#xff0c;不能是整数格式。使用to_f。
在views/home/index.html.erb&#xff0c;从bootstrap拷贝下来进度条代码&#xff0c;并修改?&#xff1a;
<% if user_signed_in? %>
<% end %>
这样进度条就可以根据数据库传来的数据显示进度了。
下一步是对进度条的说明&#xff0c;即缺哪一项&#xff1a;
- 在进度条下使用✅&#xff0c;❌图标和说明文字。
使用fontawesome.com的图标&#xff0c;把连接粘贴到内
"stylesheet" href&#61;"https://use.fontawesome.com/releases/v5.8.1/css/all.css" integrity&#61;"sha384-50oBUHEmvpQ&#43;1lW4y57PTFmhCaXp0ML5d60M1M7uH2&#43;nqUivzIebhndOJK28anvf" crossorigin&#61;"anonymous">
在index.html.erb上加上&#xff1a;
- <%&#61; current_user.onboarding_percent %>%
- <% if current_user.twitter? %>class&#61;"far fa-check-circle"><% else %>class&#61;"far fa-window-close"><% end %>Add your Twitter profile
- <% if current_user.teams.any? %>class&#61;"far fa-check-circle"><% else %>class&#61;"far fa-window-close"><% end %>Create a team
重构&#xff1a;
上面的代码可以重构&#xff1a;使用helper
如果&#xff1a;
- index内的代码太多
- onboarding功能的代码反复使用
那么&#xff0c;可以用一个helper方法。
index.html.erb
<% if user_signed_in? %>Onboarding <%&#61; current_user.onboarding_percent.round%>% Complete
<% end %>
helper方法&#xff1a;
module ApplicationHelper
...def onboarding_step_icon(step_completed)color &#61; step_completed ? "text-success" : "text-muted"tag.i class: [&#39;fas&#39;, "fa-check", color]end
end
# tag.
user.rb中的user类内的实例方法的重构&#xff0c;
如果&#xff1a;
- 方法非常多&#xff0c;不方便区分。
- 很多方法只用于某一个功能。
那么&#xff0c;就可以把部分方法放到一个模块内&#xff0c;让User类include这个类。
例如&#xff1a;
module UserOnboardingextend ActiveSupport::Corcerndef onboarding_percentsteps &#61; [:twitter?, :has_team?]complete &#61; steps.select{ |step| send(step)}complete.length / steps.length.to_f * 100enddef has_team?teams.any?end
end
然后user.rb内include UserOnboarding