Magic
```ruby
class Example
def self.after(*names)
names.each do |name|
m = instance_method(name.to_s)
# override old method
define_method(name.to_s) do |*args, &block|
m.bind(self).(*args, &block) # 這裡執行了 test method
yield(self, name.to_sym, *args) # 這裡才是真正 callback 發生的地方
self
end
end
end
def test(arg1, options)
# do someting...
# self => instance of Example
end
after(:test) do |example_instance, test_hash, arg1, options|
#example_instance => instance of Example, self, from test method
#test_hash => :test
end
end
```
https://ruby-doc.org/core-2.2.0/UnboundMethod.html#method-i-bind
2017年8月22日 星期二
rails 可以自己定義 model callback
滿實用的,但應該少用,正常的 lifecycle 能夠滿足就不應該增加新的東西
想到最有可能會用的的地方就是搭配 sub/pub design pattern 的時候,例如 publish 後要 broadcast `published` event
http://vinsol.com/blog/2014/07/07/custom-model-callbacks-in-rubyonrails/
想到最有可能會用的的地方就是搭配 sub/pub design pattern 的時候,例如 publish 後要 broadcast `published` event
http://vinsol.com/blog/2014/07/07/custom-model-callbacks-in-rubyonrails/
2017年8月17日 星期四
postgresql explain
可以看 sql 的複雜度和 cost,很方便的 sql command
https://www.postgresql.org/docs/9.4/static/using-explain.html
2017年8月15日 星期二
devise and warden - 登入失敗寄信
使用 lockable 或是不使用 lockable 都行
`DeviseController#require_no_authentication` 時會 call `warden.authenticate?`,這時會引發 `Lockable#valid_for_authentication?` 裡面的 `self.failed_attempts += 1`
也就是說當 code 運行到 `Devise::Users::SessionsController#create` 時就已經因為 before_action 而將 `failed_attempts` +1, 這時理論上只需要再 call `warden.authenticated?` 就可以知道是否驗證成功了
請把寄信邏輯寫在這(範例):
```ruby
def create
send_email if !warden.authenticated?
super do |user|
SendAdminLoginToSlack.perform_async(user.id) if user.supervisor?
Sendcloud::SuccessfulLoginSender.perform_async(user.id) if login_with_different_ip?(user)
end
flash.delete :notice
end
```
`DeviseController#require_no_authentication` 時會 call `warden.authenticate?`,這時會引發 `Lockable#valid_for_authentication?` 裡面的 `self.failed_attempts += 1`
也就是說當 code 運行到 `Devise::Users::SessionsController#create` 時就已經因為 before_action 而將 `failed_attempts` +1, 這時理論上只需要再 call `warden.authenticated?` 就可以知道是否驗證成功了
請把寄信邏輯寫在這(範例):
```ruby
def create
send_email if !warden.authenticated?
super do |user|
SendAdminLoginToSlack.perform_async(user.id) if user.supervisor?
Sendcloud::SuccessfulLoginSender.perform_async(user.id) if login_with_different_ip?(user)
end
flash.delete :notice
end
```
2017年8月13日 星期日
CSS Grid
推薦連結:
https://www.youtube.com/watch?v=txZq7Laz7_4&feature=share
TL;DR:
CSS grid 先把畫面切隔成不同的區塊後再把 content 丟到區塊裡,符合設計直覺
只套用第一層子元素
做 RWD 很方便,且省略了很多不必要的 nested elements
挺酷的
https://www.youtube.com/watch?v=txZq7Laz7_4&feature=share
TL;DR:
CSS grid 先把畫面切隔成不同的區塊後再把 content 丟到區塊裡,符合設計直覺
只套用第一層子元素
做 RWD 很方便,且省略了很多不必要的 nested elements
挺酷的
2017年8月1日 星期二
蒙地卡羅演算法
很簡單易懂的介紹,很棒
原理就是產生極多數的樣本,根據樣本的分佈狀態來預估真實狀態
其中交通堵塞的例子真的是很經典,很久以前就聽過但不知道是用蒙地卡羅演算法證明的
訂閱:
文章 (Atom)