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




2016年6月23日 星期四

ActiveRecord 後可用 select, sort_by, group_by

語句複雜很多table互相牽動時,sql的部分可以簡單化


Ex:

user = [
{ name: "C", is_admin: true, department: 20 },
{ name: "A", is_admin: true, department: 20 },
{ name: "B", is_admin: true, department: 25 },
{ name: "E", is_admin: true, department: 25 },
{ name: "D", is_admin: true, department: 25 },
{ name: "F", is_admin: false, department: 25 },
]

user = User.alluser.select! { |u| u[:is_admin] }
user_hash = user.group_by { |u| u[:department] }
user_hash.each { |k, v| v.sort_by! { |x| x[:name] } }

user_hash =
{20=>
[{:name=>"A", :is_admin=>true, :department=>20},
{:name=>"C", :is_admin=>true, :department=>20}],
25=>
[{:name=>"B", :is_admin=>true, :department=>25},
{:name=>"D", :is_admin=>true, :department=>25},
{:name=>"E", :is_admin=>true, :department=>25}]}



2016年4月22日 星期五

each_with_object 好用的地方

each_with_object 好用的地方

Ex:(多維展開)

{原本}
def org_users(users)
  temp = {}
  users.each do |user|
    temp[user.group] ||= {}
    temp[user.group][user.id] = user
  end
  temp
end

{改良}
users.each_with_object(Hash.new{ |h,k| h[k] = {} }) { |obj, hash| hash[obj.group][obj.id] = obj }



Ex:(類型計算)

x = ["tiger", "tiger", "cat", "tiger", "dog", "cat"]
x.each_with_object(Hash.new(0)) { |obj, counts| counts[obj] += 1 }


2016年4月14日 星期四

『*』的用法


「*」的用法 

把 array 展開成豆號分隔的 參數


Ex1:
numbers = [1, 2, 3]
numbers_with_zero_and_100 = [0, *numbers, 100] # => [0, 1, 2, 3, 100]

 Ex2:

def get_year_month
  year_month ||= params[:year_month] || Date.today.strftime("%Y-%m")
  year_month.split(/-|\/|_/).map { |i| i.to_i }
end
Date.new(*(get_year_month)) # =>  Fri, 01 Apr 2016