2018年5月25日 星期五

常見問題推薦解法 NoMethodError: undefined method '[]' for nil:NilClass


解決常見的
NoMethodError: undefined method '[]' for nil:NilClass


Ruby 2.3.0 之後才能用

    params = { user: { address: { street: '123 Fake Street', town: 'Faketon', postcode: '12345' } } }
   
    street = params[:user] && params[:user][:address] && params[:user][:address][:street]
   
    street = params.dig(:user, :address, :street)

    street = user&.address&.street


Ruby 2.3 以前

安裝 gem 'ruby_dig'

另一種常見的情況
h = {}
h[:a][:b][:c] = "abc" # NoMethodError: undefined method '[]' for nil:NilClass 

h = Hash.new{ |h,k| h[k] = Hash.new(&h.default_proc) }
h[:a][:b][:d][:c] = "abc" # { :a => { :b => { :c => "abc" } } }





新的分頁 gem


控制分頁系統的 gem 

pagy
https://github.com/ddnexus/pagy

看起來很厲害的 樣子 XD

2018年2月9日 星期五

capistrano 後 可以寫入 git 資訊


config/deploy.rb

namespace :deploy do
  after :finishing, :git_ionfo do
    on roles(:all) do
      version = %x(git log -1 --pretty='format:%H')
      execute "echo '#{version.strip}' > #{release_path}/.git_version"

      tag = %x(git describe --tags --always --long --dirty)
      execute "echo '#{tag.strip}' > #{release_path}/.git_tag"

      branch = %x(git rev-parse --abbrev-ref HEAD)
      execute "echo '#{branch.strip}' > #{release_path}/.git_branch"
    end
  end 
end