<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Kuro Sean on Medium]]></title>
        <description><![CDATA[Stories by Kuro Sean on Medium]]></description>
        <link>https://medium.com/@kurosean?source=rss-eadb21fcb571------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*OMfddNGFumyeEwFW.</url>
            <title>Stories by Kuro Sean on Medium</title>
            <link>https://medium.com/@kurosean?source=rss-eadb21fcb571------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 05:42:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kurosean/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Redis cluster in Rails6 cache store]]></title>
            <link>https://medium.com/@kurosean/redis-cluster-in-rails6-cache-store-7634e11cf841?source=rss-eadb21fcb571------2</link>
            <guid isPermaLink="false">https://medium.com/p/7634e11cf841</guid>
            <category><![CDATA[redis-cluster]]></category>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[rails]]></category>
            <dc:creator><![CDATA[Kuro Sean]]></dc:creator>
            <pubDate>Tue, 15 Sep 2020 15:14:03 GMT</pubDate>
            <atom:updated>2020-09-15T15:14:03.507Z</atom:updated>
            <content:encoded><![CDATA[<p>筆記一下在 Rails 6 下用 Redis cluster 作為 cache store 踩的一些雷</p><h3>取得 redis instance</h3><p>把 rails 從 5升級到6時，redis的版本從 4.1.3 到 4.2.1</p><p>從原本的</p><pre><em>Rails.cache.instance_variable_get(:@data)</em></pre><p>變成</p><pre>Rails.cache.redis</pre><p>然後原本的方法會 return nil</p><h3>在Redis cluster 下取得所有 cache keys</h3><p>在只有一台 Redis server 的時候，不建議在 production 環境下用 keys 來取得所有的 key，都說要用 scan 或是 scan_each 因為用 keys 會 block 住 process，不過在有 Redis cluster 的時候可以用 keys 因為他會自己去抓 slave（<a href="https://github.com/redis/redis-rb/blob/a2c562c002bc8f86d1f47818d63db2da1c5c3d3f/lib/redis/cluster.rb#L136">參考link</a>)，然後在有 Redis cluster的情況下不管是 Redis 4.1.3 或 Redis 4.2.1 不支援 scan or scan_each，經過實測 4.1.3 的版本會隨機抓一台回傳該node的key，在 4.2.1的版本會固定抓一台回傳 key。</p><p>所以要抓在不同node上的所有 cache key就要用到</p><pre>Rails.cache.redis.keys</pre><p>不過上面的方法會回傳所有 node 上所有的 key，不管這個key是在哪個 namespace 下，所以會需要自己手動 filter</p><pre>Rails.cache.redis.keys.select { |key| key.include?(&#39;cache&#39;)}</pre><h3>在Redis cluster下刪除多個 key</h3><p>在只有一台Redis的情況下會用下面幾種方法來一次刪除多個key</p><pre>Rails.cache.delete_matched(*)<br>Rails.cache.redis.del(*keys)</pre><p>但上面那兩個方法在有Redis cluster的情況下會噴這樣子的Error</p><pre><em>Redis::CommandError (CROSSSLOT Keys in request don&#39;t hash to the same slot)</em></pre><p>意思是在這些你要刪除的 key裡面他們並不屬於同一個 slot 所以不能刪，可以看到下圖，即使 key是寫在同一台 node 上但每個 key也可能會屬於不同的 slot，slot 的數量是從 0 ~16383 所以有 16384 個，在寫值進去的時後 redis 會根據你的 key來計算他要放在哪一台 node 的哪個 slot。</p><p>Reference: <a href="https://made.livesense.co.jp/entry/2018/10/17/135245">RubyのRedis Client LibraryをCluster Modeに対応させた話</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/301/0*LWPdwbm0l-z3Hfo8.png" /></figure><p>這邊有兩個解法</p><h4>解法ㄧ</h4><p>在寫 key 的時候加上 hashtag 像是下面這樣</p><pre>Rails.cache.fetch(&quot;my-key{123}&quot;){ 123 }</pre><p>在 key name 裡面加上 {} 並在裡面寫一個名稱（數字或文字），當有用一樣的hashtag的時候這個key就會被放在同樣的slot裡面，但用這個方法的時候要很小心，因為這代表你可能會寫大量個key到同一台node的同個 slot裡導致每台機器的資源分配不平均</p><p>Reference: <br><a href="https://redis.io/topics/cluster-spec">https://redis.io/topics/cluster-spec</a> (Keys hash tags)<br><a href="https://medium.com/@ngtzeyang94/the-inconspicuous-codis-redis-cluster-crossslot-bug-b2b7a33bf9e9">The Inconspicuous Codis/Redis cluster CrossSlot bug</a><br><a href="https://aws.amazon.com/tw/premiumsupport/knowledge-center/elasticache-crossslot-keys-error-redis/">https://aws.amazon.com/tw/premiumsupport/knowledge-center/elasticache-crossslot-keys-error-redis/</a><br><a href="https://zhuanlan.zhihu.com/p/69800024">你不知道的Redis：RedisCluster与JedisCluster</a></p><h4>解法二</h4><p>上面的解法一不算是一個很好的解法，所以解法二的做法是根據 key name 來找出 slot number ，然後把同樣一個 slot number 的 key 一次用 del 刪除</p><pre>cache_keys = Rails.cache.redis.keys.select { |key| key.include?(&#39;cache&#39;)}</pre><pre>result = cache_keys.group_by { |key| Rails.cache.redis.cluster(:keyslot, key) }</pre><pre>result.values.each { |keys| Rails.cache.redis.del(keys) }</pre><p>這邊會看到一個這樣子的方法 Rails.cache.redis.cluster(:keyslot, key) 這個就是根據 key name 來找出 slot number。有去翻 Redis source code的話可能也會看到這樣的方法</p><pre># <a href="https://github.com/redis/redis-rb/blob/8b01ab67c65b65ae2e26bbb9695ec46572bef75e/lib/redis/cluster/key_slot_converter.rb">lib/redis/cluster/key_slot_converter.rb</a><br>Redis::Cluster::KeySlotConverter.convert(key)</pre><p>我自己實測之後是發現這樣的結果</p><pre>irb(main):063:0&gt; Rails.cache.redis.cluster(:keyslot, &#39;cache:aaa{cache}&#39;)<br>=&gt; 9427<br>irb(main):064:0&gt; Rails.cache.redis.cluster(:keyslot, &#39;cache:bbb{cache}&#39;)<br>=&gt; 9427<br>irb(main):065:0&gt; Redis::Cluster::KeySlotConverter.convert(&#39;cache:aaa{cache}&#39;)<br>=&gt; 1983<br>irb(main):066:0&gt; Redis::Cluster::KeySlotConverter.convert(&#39;cache:bbb{cache}&#39;)<br>=&gt; 4929<br>irb(main):067:0&gt;</pre><p>在沒有用hashtag的情況下出來的 slot number 會是一樣的，但對於有用 hashtag的 key 出來的 slot number會是不一樣的，所以保險起見我這邊就用Rails.cache.redis.cluster(:keyslot, key)</p><p>現在有遇到的雷就這樣，在 Rails 上用 Redis cluster 有比想像中還多問題，主要是因為不夠瞭解，如果之後還有遇到其他問題的話再來更新這篇文章</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7634e11cf841" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[終於搞懂如何 revert merge commit]]></title>
            <link>https://medium.com/@kurosean/%E7%B5%82%E6%96%BC%E6%90%9E%E6%87%82%E5%A6%82%E4%BD%95-revert-merge-commit-a034b9e69fef?source=rss-eadb21fcb571------2</link>
            <guid isPermaLink="false">https://medium.com/p/a034b9e69fef</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[revert]]></category>
            <dc:creator><![CDATA[Kuro Sean]]></dc:creator>
            <pubDate>Wed, 09 Sep 2020 13:54:34 GMT</pubDate>
            <atom:updated>2020-09-09T13:54:34.877Z</atom:updated>
            <content:encoded><![CDATA[<p>在實務上一定會遇到的一個情況是當你開發完新 feature 然後你把 feature branch merge回 develop branch後，然後被告知誒～那個 feature 不用做了或是那個 feature 不是這個 release 要出，這時候你就會需要把你的已經merge進develop的commit revert掉。</p><p>下面的內容是讀完這篇文章 <a href="https://juejin.im/post/6844903590545506312">当你决定去 revert 一个merge commit</a> 然後加上自己的想法跟加上一些圖片來更好理解如何 revert merge commit</p><p>以下圖片的master branch都請視為 develop branch</p><h3>準備</h3><h4>Step1</h4><pre># 建一個 revert-merge-commit-demo 資料夾出來<br>mkdir revert-merge-commit-demo</pre><pre># 進去這個資料夾裡<br>cd revert-merge-commit-demo</pre><pre># 初始化 git<br>git init</pre><p>做完上面的動作後接下來要模擬在 develop branch 上已經有的 commit，建立兩個檔案然後分別commit</p><pre>echo &#39;file1&#39; &gt; file1 <br>git add . &amp;&amp; git commit -m &#39;commit 1&#39;<br>echo &#39;file2&#39; &gt; file2<br>git add . &amp;&amp; git commit -m &#39;commit 2&#39;</pre><p>線圖會是這樣</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*Youf9vQRSFwyrMooT7iF4A.png" /></figure><h4>Step2</h4><p>接下來就要開發新 feature 了，所以我們從 develop branch 切一個 feature branch，這邊的 branch name就叫做 feature</p><pre>#checkout 一個新的 branch 出來並且切到該 branch<br>gcb feature</pre><pre># 建立兩個 file 並且分開 commit<br>echo &#39;feature-file3&#39; &gt; feature-file3<br>git add . &amp;&amp; git commit -m &#39;feature - commit 1&#39;<br>echo &#39;feature-file4&#39; &gt; feature-file4<br>git add . &amp;&amp; git commit -m &#39;feature - commit 2&#39;</pre><p>線圖會是這樣</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*mrpBJd62nRTtVnn8_bOrOg.png" /></figure><h4>Step3</h4><p>在開發 feature 的途中，其他人還是會繼續merge 他的們 feature branch 進去develop，所以現在 develop 有4個 commit</p><pre>git checkout develop<br>echo &#39;file5&#39; &gt; file5<br>git add . &amp;&amp; git commit -m &#39;commit 3&#39;<br>echo &#39;file6&#39; &gt; file6<br>git add . &amp;&amp; git commit -m &#39;commit 4&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/738/1*l2S7b-ORauSzPKha7jGSdw.png" /></figure><h4>Step4</h4><p>feature branch 開發完了，這時候要merge進 develop 了，為了線圖要有小耳朵（什麼是小耳朵看這邊 <a href="https://gitbook.tw/chapters/branch/merge-commit.html">為什麼我的分支都沒有「小耳朵」</a>），所以我們要用 --no-ff 參數來merge，在github的 pull request 的merge功能也會有小耳朵</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/636/1*qkHoW0ua3nr9WXQp2TdeeA.png" /></figure><pre>git checkout develop<br>git merge feature --no-ff</pre><p>merge之後的線圖會長這樣，紅色那一條就是你的 feature branch，da3d4ab 這個 commit 點就是 merge feature branch 的 commit。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*GH9lxJ1OpCmuV473Z0Jwxw.png" /></figure><h4>Step5</h4><p>merge了 feature branch 之後，又有其他的人merge 進 develop</p><pre>echo &#39;file7&#39; &gt; file7<br>git add . &amp;&amp; git commit -m &#39;commit 5&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*bVyLUJBwxhMX9F9UhFMysQ.png" /></figure><h4>Step6</h4><p>然後因為某些原因，你原本開發的feature不需要了，所以你必須在develop branch revert 你的 commit ，也就是圖片裡的 da3d4ab commit。</p><p>之後就會噴error說你需要帶一個 -m 的 option</p><pre>git revert da3d4ab</pre><pre># error<br>error: commit da3d4ab5536f32adcc988db5444faeba0ee5888b is a merge but no -m option was given.<br>fatal: revert failed</pre><p>會出現這個 error 的原因是因為對於這個 merge commit (da3d4ab)的來說他有兩個 parent，一個是 develop branch 另一個是 你的 feature brach</p><pre>git show da3d4ab</pre><pre>commit da3d4ab5536f32adcc988db5444faeba0ee5888b<br>Merge: 27f07ae 75add2e （兩個 parent commit)<br>Author: sean huang &lt;<a href="/service/mailto:sean.huang@tarokosoftware.com">sean.huang@tarokosoftware.com</a>&gt;<br>Date:   Wed Sep 9 20:46:22 2020 +0800</pre><pre>Merge branch &#39;feature&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*JWSxymAP13pBi6jv3nfbfw.png" /></figure><p>因為有兩個 parent commit 所以 git 不知道到底要拿哪一個 commit 來跟 merge commit 來做 diff ，所以需要給 -m 的參數告訴他說要跟哪個 parent commit做 diff，要跟 parent1 的 commit 做 diff的話參數就帶 -m 1 ，要跟parent2做diff的話就帶 -m 2</p><p>因為 merge commit是我們不想要的，所以就要跟有 parent1的develop branch做diff，之後就可以看到多了一個commit 是把我們在feature branch建的兩個檔案刪掉</p><pre>git revert da3d4ab -m 1</pre><pre>[master 04d50b3] Revert &quot;Merge branch &#39;feature&#39;&quot;<br> 2 files changed, 2 deletions(-)<br> delete mode 100644 feature-file3<br> delete mode 100644 feature-file4</pre><p>線圖會長這樣</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*U_ezpv5bNoNWkjZvlZF6eQ.png" /></figure><h4>Step7</h4><p>那如果我們是跟在 feature branch的 commit (75add2e)做 diff 會怎樣呢？</p><pre># 先 reset head 到 revert之前的狀態，也就是 reset 到 commit5<br>git reset --hard c69e047</pre><pre># 列出現在有的檔案<br>ls # feature-file3 feature-file4 file1 file2 file5 file6 file7</pre><pre># 跟 parent2 的 commit做 diff<br>git revert da3d4ab -m 2</pre><pre>[master a82163e] Revert &quot;Merge branch &#39;feature&#39;&quot;<br> 2 files changed, 2 deletions(-)<br> delete mode 100644 file5<br> delete mode 100644 file6</pre><p>這邊會發現在 commit3 跟 commit4 加的 file5 跟 file6 被刪掉了，所以他是把feature branch 從開始到結束這段時間在 develop branch的 commit 內容都刪掉了</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*gLWNAcPe2wLhIPdoqgIs1w.png" /></figure><h3>結論</h3><ol><li>對於單一一個parent的 commit 用 git revert COMMIT_ID</li><li>對於有兩個parent的commit要帶 -m 的option，通常會帶 1 （就是你merge進去的那個branch)</li></ol><pre>git revert COMMIT_ID -m PARENT_ID</pre><p>3. 從feature branch merge到 develop 的 merge commit，develop 的 parent_id 是1，feature branch 的 parent_id 是2</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a034b9e69fef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[開箱91App瘋型轉轉樂]]></title>
            <link>https://medium.com/@kurosean/%E9%96%8B%E7%AE%B191app%E7%98%8B%E5%9E%8B%E8%BD%89%E8%BD%89%E6%A8%82-7e74d402e708?source=rss-eadb21fcb571------2</link>
            <guid isPermaLink="false">https://medium.com/p/7e74d402e708</guid>
            <dc:creator><![CDATA[Kuro Sean]]></dc:creator>
            <pubDate>Fri, 28 Aug 2020 17:34:12 GMT</pubDate>
            <atom:updated>2020-08-29T05:11:00.448Z</atom:updated>
            <content:encoded><![CDATA[<p>前幾天我才在 <a href="https://www.facebook.com/ProgrammersCreateLife">I am Programmer,I have no life.</a> 裡看到下面這張圖</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*QxJlxRBJ4TFPagZvIAcEgg.png" /></figure><p>看到的時候就覺得一定是惡搞才這樣寫的拉，實際上哪有人會這樣寫code</p><p>結果我今天在 <a href="https://www.facebook.com/init.kobeengineer">純靠北工程師</a>裡看到這樣的貼文</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*CRJVo8YrF8jh_LDL70vnjg.png" /></figure><p>真是不敢相信我的眼睛啊～～（已瞎</p><p>為什麼你要這樣塞資料到 Array 裡啊～～～</p><p>而且Array本來就是從0開始啊！你塞了一個 無意義，只是方便記順序 你當Array[0] 是塑膠做的喔！</p><p>底下的留言有</p><ol><li>寫得太好了！完全符合KISS(Keep It Simple, Stupid)原則</li><li>有註解，是個好工程師</li><li>PM : 你今天績效不錯 ！寫了很多行code</li></ol><p>剛好下面有人貼了網站連結 <a href="http://tw.91app.com/act/20200818001257/">http://tw.91app.com/act/20200818001257/</a></p><p>所以我就決定來開箱一下這個網站，看到底會有多少令人吐槽的code在裡面</p><p>首先這是網站長的樣子（為了之後網站可能會被拿掉我盡量放圖上來</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*SqwoI9QFb_gV2EdVIk79mA.png" /></figure><p>點了start 之後輪盤會開始轉，然後停下來之後就會跳一個modal</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*i0EvaDK7W3JfFnitoFI08g.png" /></figure><p>原本我還想說該不會超瞎的連這個畫面都是一個靜態圖片的，看了一下HTML還好沒有這麼瞎，不過好像也沒好到哪裡去就是。</p><p>之後點了右上角的X或是在玩一次就會重新load這個網頁</p><p>在 source code裡面也看得到這一段，嗯！真是好人工程師有加註解ＸＤ</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/928/1*OLlN_-4ez9O3Szud5w6GAw.png" /></figure><p>在玩了三次之後就會出現這樣的畫面</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*sbTKg3xNqQS69GEePG9bCQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*wLrqBOprF1WqIMvIwWNXYA.png" /></figure><p>根據遊戲規則</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*3_NrJNe_pHpC3U025nWmGg.png" /></figure><p>耶…..不過到這個網頁也不用登入會員就可以玩了說（好佛心</p><p>好了大概介紹完這個網站，接下來就實際來開箱</p><p>首先既然有遊玩次數的限制，那就代表一定有一個地方會記錄玩家玩了幾次</p><p>所以我們先來看一下有沒有任何的request送出去給 server，打開devtool看了一下 Network裡的XHR，在我點下跟轉盤結束後並沒有任何的request送出去，即使之後網頁重新載入後也沒有收到任何的 GET request 那就代表，這個網頁完全沒有跟伺服器溝通，不管是記錄遊玩幾次或是折價券的號碼甚至到所謂的輪盤隨機的結果，實作完全在前端。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*pqQ2dasbiT1fovcTO8HofQ.gif" /></figure><p>所以這時候就來合理的判斷一下可能是記在 cookie 上，那我們就來翻一下 cookie吧。看了一下cookie果然有一個叫 count_ 開頭的 cookie name，然後他的值是 2。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fXSZmogAHAfHNFXBlVah4Q.png" /></figure><p>所以只要改了這個值以後應該就可以再重新玩了，不然開無痕模式或是清cookie都可以</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*TTjDWC_cB8uWBset3Wv30w.gif" /></figure><p>接下來就是要來看 source code了</p><p>打開 source code就馬上看到令人崩潰的程式碼</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dailzF52KQa1MzXtj0s__g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*_dnOTsSDSRZLi3G9mRTHfw.gif" /></figure><p>這個長長長長的Hash是怎麼回事啊！！！<br>讓我想起了這個廣告</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FYNEGL-I-5vs%3Fstart%3D13%26feature%3Doembed%26start%3D13&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DYNEGL-I-5vs&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FYNEGL-I-5vs%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1c2564437e5e657cdb036861ed522b4/href">https://medium.com/media/d1c2564437e5e657cdb036861ed522b4/href</a></iframe><p>大佬～不是code 寫得越多行領的錢就越多啊～～<br>看起來那個很長的hash是要記錄隨機到什麼數字就要跳哪一個獎項，我們等等再來看那個部分。</p><p>現在我們先來看獎項的折價券序號，在code裡面有發現這樣的東西。<br>嗯～看起來就是儲存折價券的地方啊～</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KizaTXg023W10ejhGLPxqQ.png" /></figure><p>不過title的地方有Unicode編碼看不太出來是什麼，好險這個gift變數是寫全域的，那我們就在 console裡 log出來看看吧</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*tdGi9h3_tLVezw9tFjs-AA.gif" /></figure><p>好喔～看起來我們連轉盤都不用轉了直接在 console 裡下 gift 按Enter 就可以知道所有的折價碼了（草</p><p>接下來我們來看看有沒有辦法是可以不用改寫 cookie的值就可以玩很多次</p><p>在 code裡有這麼一段，看起來是主要負責判斷有沒有超過3次的邏輯<br>有一個變數叫 total_of_day 看起來就是記上限次數，然後 count_check 的function是來檢查有沒有玩超過三次，function裡面的get_count 應該就是從cookie取出value，所以兩個數字相減之後如果沒有大於0就代表已經不能玩了</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*xKTogc1NOuUz9ONW7iW-fg.png" /></figure><p>要是我們能改寫 total_of_day的數字的話那是不是就可以玩超多次了！</p><p>那我們來實際試試看，步驟是這樣的</p><ol><li>把cookie的值改成3，顯示出到達遊玩上限的畫面</li><li>切到console去把 total_of_day 改成99999</li><li>重新整理畫面看能不能在玩一次</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Web6NPwtNlkNpWtsrqLd1g.gif" /></figure><p>嗯？看起來好像沒用耶？為什麼？</p><p>其實原因是在一開始程式執行的時候就已經做好檢查了</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*c1vOEMQd_Vs5uNt-3zPWFw.png" /></figure><p>所以之後去console改值也沒有用，不過難道這樣就放棄了嗎</p><p>不！！還沒，所以我們要找另一個方法，既然畫面一重整程式就會執行的話，那我們就在他執行之前下中斷點去改值不就好了</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*MqwLgsziSZDCj__Li0iThw.png" /></figure><p>JS執行的順序會是 變數先被定義然後後來才是function會被定義，所以我們在 total_of_day 的之後下中斷點跟count_check function裡的remaining下中斷點，所以我們的程式執行的順序會是</p><ol><li>total_of_day 先被定義為 3</li><li>中斷停在179行</li><li>之後到console去把 total_of_day 設為 99999</li><li>之後跳到下一個中斷點就可以看到 total_of_day變99999，所以 99999–3大於0，所以就可以繼續玩了～～（撒花</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ie_p5zCp3Z-wzI_U8u4igA.gif" /></figure><p>最後其實如果想要一直玩的話也不用這麼麻煩拉直接把cookie的值改成一個超大的負數就好，這樣就可以一直轉下去</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zCJAFBNCjPTp-p45fguxDw.png" /></figure><p>講完怎麼無限轉轉轉之後還是要來code review一下</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/1*dGvTkDIRiuIKw3Wx7woiBQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/998/1*5itEjPlATj6JpkojQBxldg.png" /></figure><p>如果只是要根據gift裡的id來決定要加麼class的話，直接寫這樣不好嗎？</p><pre>$(&quot;.game_outer ul li:nth-child(1) img&quot;).addClass(`game${id}`);</pre><p>看起來那個 GAME 的Array也沒用到其他地方了，然後如果真的要塞Array的話可以直接塞拉</p><pre>const GAME = [&quot;game_01&quot;, &quot;game_02&quot;, ....]</pre><p>要比較炫炮一點的可以這樣塞</p><pre>Array.from(Array(8), (_, i) =&gt; `game0${i+1}`)<br># =&gt; [&quot;game01&quot;, &quot;game02&quot;, &quot;game03&quot;, &quot;game04&quot;, &quot;game05&quot;, &quot;game06&quot;, &quot;game07&quot;, &quot;game08&quot;]</pre><p>然後可以好好正視一下Array的index是從0開始這件事嗎，一直逃避也不是辦法阿～</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OP9UfbchJtOY3mLM3MaFlQ.png" /></figure><p>然後看起來下面這一段code完全沒用到啊，資料裡面的type也只有code沒有link</p><pre>if (gift.type == &#39;code&#39;) {<br>  type = 1;<br>} else if (gift.type == &#39;link&#39;) {<br>  type = 2;<br>}</pre><pre>--------------</pre><pre>$(PRIZE[type]).delay(3500).fadeIn(300);<br># PRIZE的array看起來也只有用到1而已</pre><p>再來就是那個長長長長的Hash了</p><pre>var lottery = {<br>    &quot;1&quot;: 1,<br>    &quot;2&quot;: 2,<br>    &quot;3&quot;: 2,<br>    &quot;4&quot;: 2,<br>    &quot;5&quot;: 2,<br>    &quot;6&quot;: 2,<br>    &quot;7&quot;: 2,<br>    &quot;8&quot;: 2,<br>    &quot;9&quot;: 2,<br>    &quot;10&quot;: 2,<br>    &quot;11&quot;: 2,<br>    &quot;12&quot;: 2,<br>    &quot;13&quot;: 2,<br>    &quot;14&quot;: 2,<br>    &quot;15&quot;: 2,<br>    &quot;16&quot;: 2,<br>    &quot;17&quot;: 2,<br>    &quot;18&quot;: 2,<br>    &quot;19&quot;: 2,<br>    &quot;20&quot;: 2,<br>    &quot;21&quot;: 2,<br>    &quot;22&quot;: 2,<br>    &quot;23&quot;: 2,<br>    &quot;24&quot;: 2,<br>    &quot;25&quot;: 2,<br>    &quot;26&quot;: 2,<br>    &quot;27&quot;: 2,<br>    &quot;28&quot;: 2,<br>    &quot;29&quot;: 2,<br>    &quot;30&quot;: 2,<br>    &quot;31&quot;: 2,<br>    &quot;32&quot;: 3,<br>    &quot;33&quot;: 3,<br>    &quot;34&quot;: 3,<br>    &quot;35&quot;: 3,<br>    &quot;36&quot;: 3,<br>    &quot;37&quot;: 3,<br>    &quot;38&quot;: 3,<br>    &quot;39&quot;: 3,<br>    &quot;40&quot;: 3,<br>    &quot;41&quot;: 3,<br>    &quot;42&quot;: 3,<br>    &quot;43&quot;: 3,<br>    &quot;44&quot;: 3,<br>    &quot;45&quot;: 3,<br>    &quot;46&quot;: 3,<br>    &quot;47&quot;: 4,<br>    &quot;48&quot;: 4,<br>    &quot;49&quot;: 4,<br>    &quot;50&quot;: 4,<br>    &quot;51&quot;: 5,<br>    &quot;52&quot;: 6,<br>    &quot;53&quot;: 6,<br>    &quot;54&quot;: 6,<br>    &quot;55&quot;: 6,<br>    &quot;56&quot;: 6,<br>    &quot;57&quot;: 6,<br>    &quot;58&quot;: 6,<br>    &quot;59&quot;: 6,<br>    &quot;60&quot;: 6,<br>    &quot;61&quot;: 6,<br>    &quot;62&quot;: 6,<br>    &quot;63&quot;: 6,<br>    &quot;64&quot;: 6,<br>    &quot;65&quot;: 6,<br>    &quot;66&quot;: 6,<br>    &quot;67&quot;: 6,<br>    &quot;68&quot;: 6,<br>    &quot;69&quot;: 6,<br>    &quot;70&quot;: 6,<br>    &quot;71&quot;: 6,<br>    &quot;72&quot;: 6,<br>    &quot;73&quot;: 6,<br>    &quot;74&quot;: 6,<br>    &quot;75&quot;: 6,<br>    &quot;76&quot;: 6,<br>    &quot;77&quot;: 6,<br>    &quot;78&quot;: 6,<br>    &quot;79&quot;: 6,<br>    &quot;80&quot;: 6,<br>    &quot;81&quot;: 6,<br>    &quot;82&quot;: 7,<br>    &quot;83&quot;: 7,<br>    &quot;84&quot;: 7,<br>    &quot;85&quot;: 7,<br>    &quot;86&quot;: 7,<br>    &quot;87&quot;: 7,<br>    &quot;88&quot;: 7,<br>    &quot;89&quot;: 7,<br>    &quot;90&quot;: 7,<br>    &quot;91&quot;: 7,<br>    &quot;92&quot;: 7,<br>    &quot;93&quot;: 7,<br>    &quot;94&quot;: 7,<br>    &quot;95&quot;: 7,<br>    &quot;96&quot;: 7,<br>    &quot;97&quot;: 8,<br>    &quot;98&quot;: 8,<br>    &quot;99&quot;: 8,<br>    &quot;100&quot;: 8<br>};</pre><p>如果真的要按照原本的順序跟值的話其實可以用 fill 來達成</p><pre>let arr = Array(100)<br>arr.fill(1,0,1)<br>arr.fill(2,1,31)<br>arr.fill(3,31,46)<br>arr.fill(4,31,50)<br>arr.fill(5,50,51)<br>arr.fill(6,51,81)<br>arr.fill(7,81,96)<br>arr.fill(8,96,100)</pre><p>不過其實這邊根本可以不用用hash，直接用array就好，而且其實機率比較小的數字放在array的哪個index被抽中的機率是一樣的，不會因為你放在第50個被抽中的機率就更低，所以可以這樣寫</p><pre>根據 gift的設定，1有1個，2有30個, 3有15個, 4有4個, 5有1個, 6有30個, 7有15個, 8有4個</pre><pre>let arr = Array(100)<br>arr.fill(1,0,1)<br>arr.fill(5,1,2)<br>arr.fill(4,2,6)<br>arr.fill(8,6,10)<br>arr.fill(3,10,25)<br>arr.fill(7,25,40)<br>arr.fill(2,40,70)<br>arr.fill(6,70,100)</pre><p>這邊只有根據現有的code來優化，至於有沒有其他更好的寫法一定有，不過我這邊就沒有要再幫refactor了</p><p>會寫這篇主要還是要說幾點</p><ol><li>要認清楚在前端處理資料並不是這麼的安全，所以資料類的東西最好都是到後端處理後再傳回去，除非今天這個轉盤只是做好玩的，或是coupon其實沒上限，不然直接放一個500塊的coupon code出來還比較快</li><li>不要把 javascript 101的練習作業拿來放在 production上，而且還是這麼大的電商，看這樣的網頁真的會擔心你們的電商真的沒問題嗎？</li><li>有人code review 很重要！很重要！很重要！</li></ol><h3>後記</h3><p>文章發了以後得到了一些迴響，看起來當初就是以行銷為目的寫的網頁</p><p>連91app都在自己的粉絲團自嘲</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vN8BiO2l7KB9Cw-e0Dp-1A.png" /></figure><p>平常我也只是偶爾幫忙寫寫前端code的小嫩嫩，不過如果這邊文章可以讓剛接觸前端的新手作為一個負面教材，知道在前端處理資料不是這麼安全的話要更警慎的話也不錯，如果也有幫助到91app做行銷的話，那一舉兩得也不錯！！</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7e74d402e708" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[用devise_invitable 做邀請功能]]></title>
            <link>https://medium.com/@kurosean/%E7%94%A8devise-invitable-%E5%81%9A%E9%82%80%E8%AB%8B%E5%8A%9F%E8%83%BD-35e2a33fbc2c?source=rss-eadb21fcb571------2</link>
            <guid isPermaLink="false">https://medium.com/p/35e2a33fbc2c</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[rails]]></category>
            <dc:creator><![CDATA[Kuro Sean]]></dc:creator>
            <pubDate>Thu, 06 Aug 2020 02:26:09 GMT</pubDate>
            <atom:updated>2020-08-06T02:26:09.531Z</atom:updated>
            <content:encoded><![CDATA[<p>最近工作上要做邀請 user 來試用產品，所以就用了 <a href="https://github.com/scambra/devise_invitable">devise_invitable</a> 來實作<br>這邊就來紀錄一下。</p><p><a href="https://github.com/scambra/devise_invitable">devise_invitable</a> 顧名思義就是 base 在 devise 這個 gem 的邀請功能，跟devise 一樣基本上只要一安裝好然後跑他的 install rake 就可以用了，controller 也不用寫view 也會建出來，但是因為 app 本身是做 api base 所以必須要把需要的功能從他的 controller 抽出來（參考他的 source code)，下面就列幾個我有用到的功能跟一些注意事項。</p><h3>1. 邀請功能 (invite!)</h3><p>用 class method invite! 就可以輕鬆的實現邀請功能，這邊要注意的是要用 class method 的 invite! ，而不是 instance method 的 invite! ，原因下面會說明。</p><pre>User.invite! ( O )<br>User.invite! ( X )</pre><p>invite! 有兩個參數，第一個參數是一個 hash， hash 裡面可以帶 email 跟skip_invitation , 第二個參數可以帶是由哪個 user 邀請的，這樣就會在那個被邀請的user身上紀錄邀請者的 id （invited_by_id)</p><pre>User.invite!(<br>  { email: &#39;someone@email.com&#39;, skip_invitation: true },<br>  current_admin<br>)</pre><p>第一個參數裡的 email 不用說就是被邀請者的 email ，在 call invite! 之後馬上就會在 DB 裡建立一個新的 user record，所以如果你同一個 email call 了兩次 invite! 第二次他會跟你說這個 email 已經存在了。</p><p>再來就是 skip_invitation ，這個參數是用來略過寄信的動作，在預設的情況下只要呼叫 invite! 除了他會建立新的 record 之外還會寄信，但我的情況是我想要自己控制寄信的部分，所以我選擇手動自己來。</p><p>另外如果用了 skip_invitation 略過寄信的話要記得 自己手動updateinvitation_sent_at 這個欄位。</p><h3>2. 信件設定</h3><p>在有設定 skip_invitation 的情況下，需要建立自己的 application mailer 跟相對應的 email template 。在沒有設定skip_invitation 的情況下有 3 個方法可以設定信件。</p><h4>Way1</h4><p>第一種是用 gem 預設的 Devise::Mailer 跟 view 去寄信，但用這個方法的人應該比較少，因為大多數都需要客製。</p><h4>Way2</h4><p>第二種是用既有的 ApplicationMailer 跟客製的 view，首先第一步要先去config/initializers/devise.rb 裡找到 config.mailer 然後把名稱改成你自己的 mailer。</p><pre>config.mailer = &#39;MyMailer&#39;</pre><p>之後如果在寄信之前不需要額外的處理的話可以不用在 mailer 裡面建立 action ，<a href="https://github.com/scambra/devise_invitable">devise_invitable</a> 預設會用 invitation_instructions<em> </em>作為 action name，所以你只要 invitation_instructions.html.erb 的 email view就好了。預設他會傳兩個有用的 instance variable 到 view裡面， ㄧ個是resource 另一個是 token ，resource 就是新建立出來的 user ， token 就是用來verify invitation 用的 token。</p><h4>Way3</h4><p>第三種是根據上面的第二種的方法然後需要在寄信前做額外的處理的情況<br>這時候就會需要建立自己的 mailer action 了，就像上面提到的預設的 mailer action name是invitation_instructions 所以我們就可以在自己的mailer裡建立一個相同名稱的action。</p><p>預設會傳三個參數到這個action裡，其實就跟上面一樣第一個是新建立的 user record，第二個是 token ，第三個參數是個 empty hash 但我不太知道什麼時候才會有值，我自己是沒用到。如果要客製化例如驗證token時的網誌之類的就可以在這邊做。</p><h3>3. 驗證</h3><p>在 API layer 可以用 find_by_invitation_token 根據傳過來的token來找到對應的 user record，然後用 accept_invitation! 來做驗證，這邊要注意的這個 method 也是要用 class method 的，然後裡面需要帶三個參數 invitation_token &amp; password &amp; password_confirmation ，在認證通過之後<br>會寫入時間到 invitation_accepted_at 的欄位，然後把 invitation_token 設為 nil。</p><pre>User.accept_invitation!(<br>  invitation_token: &#39;my random token&#39;,<br>  password: &#39;12345678&#39;,<br>  password_confirmation: &#39;12345678&#39;<br>)</pre><h3>4. helper methods</h3><ol><li>raw_invitation_token<br>回傳該 user 用來驗證用的 token（比較短的） ，不是回傳db裡的 invitation_token 。</li><li>invited_to_sign_up?<br>回傳 user 是否曾經被邀請過了</li><li>invitation_accepted? <br>回傳是否通過驗證</li></ol><p>剩下的可以參考這邊的 <a href="https://www.rubydoc.info/github/scambra/devise_invitable/Devise/Models/Invitable">documentation</a></p><h3>5. Instance method 的 invite!</h3><p>上面有提到在邀請新user時要用 class method 的 invite! 而不是用 instance method 的 invite! ，主要的原因可以根據這一篇文章 <a href="https://qiita.com/jnchito/items/689a7069f02ce14d1a3f">devise_invitableのインスタンスメソッド版invite!は、原則として保存済みのUserに対して使う</a> 裡寫的幾點來看</p><ol><li>用 User.invite! 可以透過在model裡加上 validate_on_invite: true 來在保存資料前做驗證，但如果用 user.invite! (instance method)的話就不會在儲存之前做驗證。在source code裡面似乎是用了 save(validate: false) 略過驗證了。</li><li>Instance method 的 invite! 只對已存在的 user 使用才可以避免建立出髒資料。</li></ol><p>Reference:<br><a href="https://github.com/scambra/devise_invitable">https://github.com/scambra/devise_invitable</a><br><a href="https://www.rubydoc.info/github/scambra/devise_invitable/Devise/Models/Invitable">https://www.rubydoc.info/github/scambra/devise_invitable/Devise/Models/Invitable</a><br><a href="https://code.tutsplus.com/tutorials/exploring-devise-part-2--cms-27390">https://code.tutsplus.com/tutorials/exploring-devise-part-2--cms-27390</a><br><a href="http://kaorina.hatenablog.com/entry/2016/07/22/163044">http://kaorina.hatenablog.com/entry/2016/07/22/163044</a><br><a href="https://qiita.com/jnchito/items/689a7069f02ce14d1a3f">https://qiita.com/jnchito/items/689a7069f02ce14d1a3f</a><br><a href="https://qiita.com/himatani/items/907900f1f0d0e4f379b5">https://qiita.com/himatani/items/907900f1f0d0e4f379b5</a><br><a href="https://qiita.com/tags/devise_invitable">https://qiita.com/tags/devise_invitable</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35e2a33fbc2c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[active_model_otp 筆記]]></title>
            <link>https://medium.com/@kurosean/active-model-otp-%E7%AD%86%E8%A8%98-faf4f87a3568?source=rss-eadb21fcb571------2</link>
            <guid isPermaLink="false">https://medium.com/p/faf4f87a3568</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[otp-verification]]></category>
            <category><![CDATA[rails]]></category>
            <dc:creator><![CDATA[Kuro Sean]]></dc:creator>
            <pubDate>Wed, 05 Aug 2020 08:56:42 GMT</pubDate>
            <atom:updated>2020-08-05T08:56:42.407Z</atom:updated>
            <content:encoded><![CDATA[<p>最近有用到 <a href="https://github.com/heapsource/active_model_otp">active_model_otp</a> 來做 one-time password的功能所以來紀錄一下。</p><p>otp_code 是用來產生一次性密碼的 method, 預設是 6 個數字，在產生的時候可以加上 time 的參數，主要的功能是設定這個密碼產生的時間，同時也是設定這個密碼可以開始被驗證的時間（下面會解釋）</p><p>authenticate_otp 是用來驗證一次性密碼的 method，在產生 otp code 沒有特別設定 time 的情況下 30 秒之後會過期</p><pre>user.otp_code # 123456<br>user.authenticate_otp(&#39;123456&#39;) # return 一個timestamp (密碼建立的時間)</pre><pre>30 秒之後</pre><pre>user.authenticate_otp(&#39;123456&#39;) # return nil (代表無效）</pre><p>authenticate_otp 可以透過 drift 的參數來設定密碼在某一段時間內都是有效的，這邊跟一般設定密碼的概念有點不太一樣，一般來說過期時間通常會設定在密碼身上而不是驗證端上，舉例來說就像 JWT 一樣可以設 expiresIn 但是otp這邊的運作是我每30秒都會產生一個新的code，但是驗證端可以決定這個 code 產生之後的多久之內他是有效的，用下面的例子說明。</p><pre># case 1<br>user.otp_code # 123456<br>user.authenticate_otp(&#39;123456&#39;) # valid in 30 seconds</pre><pre># case 2<br>user.otp_code # 123456<br># 30 seconds later</pre><pre># 設定密碼產生後的 600 秒以內都是有效的<br>user.authenticate_otp(&#39;123456&#39;, drift: 600) </pre><pre># case 3</pre><pre># 設定密碼為10分鐘前產生的<br>user.otp_code(time: 10.minutes.ago) # 123456</pre><pre># 因為是10分鐘前產生的，所以已經過了30秒的有效期user.authenticate_otp(&#39;123456&#39;) # return nil (代表無效）</pre><pre># case 4<br># 設定密碼為10分鐘前產生的<br>user.otp_code(time: 10.minutes.ago) # 123456</pre><pre># 設定密碼為產生後的20分鐘有效<br>user.authenticate_otp(&#39;123456&#39;, drift: 20.minutes) <br># return a timestamp</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=faf4f87a3568" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to mock function of module]]></title>
            <link>https://medium.com/@kurosean/how-to-mock-function-of-module-38c15f1f3d5f?source=rss-eadb21fcb571------2</link>
            <guid isPermaLink="false">https://medium.com/p/38c15f1f3d5f</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[jest]]></category>
            <dc:creator><![CDATA[Kuro Sean]]></dc:creator>
            <pubDate>Wed, 05 Aug 2020 08:08:22 GMT</pubDate>
            <atom:updated>2020-08-05T08:08:22.679Z</atom:updated>
            <content:encoded><![CDATA[<pre># myModule.js</pre><pre>const testFunc = () =&gt; &#39;original value&#39;;<br>export const testFunc2 = () =&gt; &#39;original value 2&#39;;</pre><pre>expect default { <br>  testFunc,<br>}</pre><p>Way 1: use mockReturnValue to mock return value.</p><pre># moModule.spec.js</pre><pre>import myModule from &#39;./myModule&#39;;</pre><pre>describe(&#39;&#39;, () =&gt; {<br>  before(() =&gt; {<br>    myModule.testFunc = jest.fn().mockReturnValue(&#39;hello world!&#39;);<br>  });</pre><pre>  it(&#39;&#39;, () =&gt; {<br>    expect(myModule.testFunc()).toEqual(&#39;hello world!&#39;); # pass<br>  });<br>});</pre><p>Way 2: use spyOn and mockImplementation to mock return value.</p><pre># myModule.spec.js</pre><pre>import myModule from &#39;./myModule&#39;;</pre><pre>describe(&#39;&#39;, () =&gt; {<br>  before(() =&gt; {<br>    jest<br>      .spyOn(myModule, &#39;testFunc&#39;)<br>      .mockImplementation(() =&gt; &#39;hello world&#39;);<br>  });</pre><pre>  it(&#39;&#39;, () =&gt; {<br>    expect(myModule.testFunc()).toEqual(&#39;hello world!&#39;); # pass<br>  });<br>});</pre><p>Way3: use jest.mock to mock specific module function</p><pre># myModule.spec.js</pre><pre>jest.mock(&#39;./myModule&#39;, () =&gt; {<br>  const module = jest.requireActual(&#39;./myModule&#39;);<br>  return {<br>    ...module,<br>    testFunc2: () =&gt; &#39;HI! world&#39;,<br>  }<br>});</pre><pre>import { testFunc, testFunc2 } from &#39;./myModule&#39;;</pre><pre>describe(&#39;&#39;, () =&gt; {<br>  it(&#39;&#39;, () =&gt; {<br>    expect(testFunc()).toEqual(&#39;original value&#39;); # pass<br>    expect(testFunc2()).toEqual(&#39;HI! world&#39;); # pass<br>  });<br>});</pre><p>Reference: <br><a href="https://github.com/facebook/jest/issues/936">https://github.com/facebook/jest/issues/936</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38c15f1f3d5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails where & update_all]]></title>
            <link>https://medium.com/@kurosean/rails-where-update-all-9384f8748b4b?source=rss-eadb21fcb571------2</link>
            <guid isPermaLink="false">https://medium.com/p/9384f8748b4b</guid>
            <category><![CDATA[rails-5]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Kuro Sean]]></dc:creator>
            <pubDate>Mon, 03 Aug 2020 07:53:54 GMT</pubDate>
            <atom:updated>2020-08-03T07:53:54.614Z</atom:updated>
            <content:encoded><![CDATA[<p>今天在review同事的PR的時候遇到了一個疑問</p><p>J: where直接接update_all應該是直接操作DB做update，不會initialize AR 或是AR relation 吧？<br>S: 嗯？是這樣嗎？我以為還是會initialize AR relation，可是這樣 in_batches 的批次更新不就沒屁用了</p><p>5 mins later</p><p>根據這邊文章<br><a href="https://blog.toshimaru.net/rails-batch-optimization/#%E6%9C%80%E9%81%A9%E5%8C%964-in_batches--update_all-%E3%82%92%E4%BD%BF%E3%81%86">https://blog.toshimaru.net/rails-batch-optimization/#%E6%9C%80%E9%81%A9%E5%8C%964-in_batches--update_all-%E3%82%92%E4%BD%BF%E3%81%86</a></p><p>看來如果是要直接update資料的話不用在多加一個 in_batches 去脫褲子放屁了</p><pre>User.where(guest: false).update_all(column: value) ( O )<br>User.where(guest: false).in_batches.update_all(column: value) ( X )</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9384f8748b4b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[TimeCop is not working when using Shared_examples]]></title>
            <link>https://medium.com/@kurosean/timecop-is-not-working-when-using-shared-examples-8ec435a2b1f?source=rss-eadb21fcb571------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ec435a2b1f</guid>
            <category><![CDATA[rspec]]></category>
            <category><![CDATA[rails]]></category>
            <dc:creator><![CDATA[Kuro Sean]]></dc:creator>
            <pubDate>Wed, 12 Feb 2020 09:39:54 GMT</pubDate>
            <atom:updated>2020-02-12T09:39:54.363Z</atom:updated>
            <content:encoded><![CDATA[<p>Incorrect way</p><pre>shared_examples &#39;my shared examples&#39; do</pre><pre>  it &#39;print time&#39; do</pre><pre><em>    # The current time should be &quot;Wed, 12 Feb 2020 06:00:00&quot; (1.hour later)</em></pre><pre><em>    # but it is &quot;Wed, 12 Feb 2020 05:00:xx&quot; (few second later)</em></pre><pre>  p Time.current</pre><pre>  end</pre><pre>end</pre><pre>context &#39;my context&#39; do</pre><pre><em>  # Time.current #=&gt; Wed, 12 Feb 2020 05:00:00</em></pre><pre>  Timecop.travel 1.hour do</pre><pre>  it_behaves_like &#39;my shared examples&#39;</pre><pre>  end</pre><pre>end</pre><p>Correct way</p><pre>context &#39;my context&#39; do</pre><pre>  before { Timecop.travel 1.hour }</pre><pre>  it_behaves_like &#39;my shared examples&#39;</pre><pre>end</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ec435a2b1f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to stub session in grape api testing]]></title>
            <link>https://medium.com/@kurosean/how-to-stub-session-in-grape-api-testing-696f35f381a1?source=rss-eadb21fcb571------2</link>
            <guid isPermaLink="false">https://medium.com/p/696f35f381a1</guid>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[rspec]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Kuro Sean]]></dc:creator>
            <pubDate>Wed, 15 Jan 2020 13:16:32 GMT</pubDate>
            <atom:updated>2020-11-17T06:57:46.083Z</atom:updated>
            <content:encoded><![CDATA[<p>End-point</p><pre>class Password &lt; Grape::API<br>  helpers do<br>    def session<br>      env[&#39;rack.session&#39;]<br>    end<br>  end<br>end</pre><p>spec</p><pre>describe &#39;POST /api/v1/password&#39; do<br>  subject { post &#39;/api/v1/password&#39;, params: {} }<br>  <br>  before do<br>    Grape::Endpoint.before_each do |endpoint|<br>      allow(endpoint).to(<br>        receive(:session).and_return(token: &#39;some token&#39;)<br>      )<br>    end<br>  end</pre><pre>  # important <br>  # Don&#39;t forgot reset Grape::Endpoint to nil, otherwise it will break whole tests when you run rspec</pre><pre>  after { Grape::Endpoint.before_each nil }</pre><pre>  it { ... }<br>end</pre><p>Reference:</p><p><a href="https://github.com/ruby-grape/grape/pull/397">https://github.com/ruby-grape/grape/pull/397</a><br><a href="https://github.com/yukihirop/onepage/commit/2a8a4ea42e9b8274589a56feebfd1e823a5c6bae">https://github.com/yukihirop/onepage/commit/2a8a4ea42e9b8274589a56feebfd1e823a5c6bae</a></p><p>2020/11/17 Update</p><p>Set session by Warden</p><pre>def _set_session(key, value)<br>  Warden.on_next_request do |proxy|<br>    proxy.raw_session[key] = value<br>  end<br>end<br><br>context &#39;When there is something&#39; do<br>  let(:yesterday) { 1.day.ago }<br>  let(:updates_enabled) { true }<br><br>  before do<br>    _set_session(:access_acount_id, user.id)<br>    login_as(user, scope: :user)<br>  end<br><br>  it &#39;does not update records&#39; do<br>    visit dashboard_path<br>    expect(page).to have_css(&#39;.popup#my-popup&#39;)<br>  end<br>end</pre><p>Reference: <a href="https://stackoverflow.com/a/61541845">https://stackoverflow.com/a/61541845</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=696f35f381a1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Array of hstore]]></title>
            <link>https://medium.com/@kurosean/array-of-hstore-8790566d1ff0?source=rss-eadb21fcb571------2</link>
            <guid isPermaLink="false">https://medium.com/p/8790566d1ff0</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Kuro Sean]]></dc:creator>
            <pubDate>Thu, 20 Jun 2019 06:28:31 GMT</pubDate>
            <atom:updated>2019-06-20T06:28:31.121Z</atom:updated>
            <content:encoded><![CDATA[<p>因為案子的需求需要在 hstore 裡面儲存 Array 資料，這邊紀錄一下實作方法跟如何使用。</p><h4>Implementation</h4><p>主要的實作方式是透過 gem Virtus 來實作，下面是簡單的 simple code</p><pre># Websites::ScanDomain</pre><pre>include Virtus.model</pre><pre>attribute :subdomain, Array[String]</pre><pre>def self.dump(params)<br>  params.to_hash<br>end</pre><pre>def self.load(params)<br>  <em># parse array string to array when load data<br>  </em>params[&#39;subdomain&#39;] = JSON.parse(params[&#39;subdomain&#39;]) if params &amp;&amp; params[&#39;subdomain&#39;]</pre><pre>  new(params)<br>end</pre><p>這邊比較要注意的地方是在 hstore 裡儲存 Array 實際上是用 JSON String 的方式去儲存 Array 資料的，像是這樣&quot;[\&quot;app.domain.io\&quot;]&quot; 。所以在從 DB 讀出來的時候要用 JSON 去把資料 parse 成 Array 格式。</p><h4>Usage</h4><p>在 model 裡可以這樣設定</p><pre>serialize :scan_domain, Websites::ScanDomain</pre><pre>Websites::ScanDomain.attribute_set.each do |attribute|<br>  delegate attribute.name, to: :scan_domain<br>  delegate &quot;#{attribute.name}=&quot;, to: :scan_domain<br>end</pre><pre># get<br>website.scan_domain = { subdomain: [&quot;app.domain.io&quot;] }<br>website.subdomain = [&quot;app.domain.io&quot;]</pre><pre>#set</pre><pre># Will automatically convert string then save data as array<br>website.subdomain = &quot;app.domain.io&quot; or</pre><pre>website.subdomain = [&quot;app.domain.io&quot;]</pre><h4>Query</h4><p>上面有提到了在 hstore 裡的 Array 實際上是用 JSON String 的格式儲存在DB裡的，所以在 query 的時候也要用 string 去找，下面列出了幾個查詢的 case<br>Reference: <a href="https://stackoverflow.com/a/35490363">https://stackoverflow.com/a/35490363</a></p><ol><li>找出沒有 subdomain 的 Record</li></ol><pre>Website.where(&quot;scan_domain -&gt; &#39;subdomain&#39; = ?&quot;, &quot;[]&quot;)</pre><pre>#=&gt; &quot;SELECT \&quot;websites\&quot;.* FROM \&quot;websites\&quot; WHERE (scan_domain -&gt; &#39;subdomain&#39; = &#39;[]&#39;)&quot;</pre><p>2. 找出特定的資料</p><pre>Website.where(&quot;scan_domain -&gt; &#39;subdomain&#39; = ?&quot;,&#39;[&quot;app.termly.io&quot;]&#39;)</pre><pre>#=&gt; &quot;SELECT \&quot;websites\&quot;.* FROM \&quot;websites\&quot; WHERE (scan_domain -&gt; &#39;subdomain&#39; = &#39;[\&quot;app.domain.io\&quot;]&#39;)&quot;</pre><pre># Do not do this</pre><pre>termly(main)&gt; Website.where(&quot;scan_domain -&gt; &#39;subdomain&#39; = ?&quot;,&quot;[&#39;app.domain.io&#39;]&quot;)</pre><pre>(O) &#39;[&quot;app.domain.io&quot;]&#39;<br>(X) &quot;[&#39;app.domain.io&#39;]&quot;</pre><p>3. 找出在 Array of hstore 裡特定的值</p><pre>Website.where(&quot;scan_domain -&gt; &#39;subdomain&#39; LIKE &#39;%app.domain.io%&#39;&quot;)<br>Website.where(&quot;scan_domain -&gt; &#39;subdomain&#39; LIKE ?&quot;,&#39;%app.domain.io%&#39;)</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8790566d1ff0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>