<?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[Ryan on Ruby/Rails - Medium]]></title>
        <description><![CDATA[Repeat what i read and met - Medium]]></description>
        <link>https://medium.com/ren-on-rails?source=rss----d14033a25b45---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Ryan on Ruby/Rails - Medium</title>
            <link>https://medium.com/ren-on-rails?source=rss----d14033a25b45---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 14:45:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/ren-on-rails" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[推書 | Ruby Under a Microscope]]></title>
            <link>https://medium.com/ren-on-rails/ruby-under-a-microscope-601a1fbe7de7?source=rss----d14033a25b45---4</link>
            <guid isPermaLink="false">https://medium.com/p/601a1fbe7de7</guid>
            <dc:creator><![CDATA[RYAN]]></dc:creator>
            <pubDate>Sat, 12 Aug 2017 16:44:30 GMT</pubDate>
            <atom:updated>2020-03-05T09:49:47.366Z</atom:updated>
            <content:encoded><![CDATA[<p>這本書適合給非初學、每天都在使用 Ruby 的開發者。</p><p>這篇只是簡短的翻譯大綱，小弟目前只啃到了第五章。從 Ruby 來探討編譯器，真的非常有趣，大多數的程式語言也是透過差不多的流程去轉化執行你的程式，如果你有其他語言的開發經驗，應該會有不少有趣的感受。</p><p>看完有時間再來針對印象深刻的章節寫文章～（應該就是沒時間了 XD）</p><h3>大綱</h3><h4>一、Tokenization and Parsing</h4><p>Ruby 如何 parse 你的程式碼? 這是電腦科學其中一個最迷人的地方。電腦語言為什麼能夠理解你寫的程式嗎? 它到底是由什麼組成的?</p><h4>二、Compilation</h4><p>Ruby 的編譯器如何在執行之前，將你的程式碼轉成不同語言。</p><h4>三、How Ruby executes your code</h4><p>看虛擬機如何執行你的程式。機器裡面有什麼東西? 為什麼它能夠完成任務? 我們將深入虛擬機去了解。</p><h4>四、Control stuctures and method dispatch</h4><p>繼續虛擬機的部分。看 Ruby 如何實作控制語法 (if..else.., while..end loop). 我們也將探討 Ruby 如何實作呼叫方法</p><h4>五、Objects and Classes</h4><p>討論 Ruby Object 與 Class 的應用。Object 跟 Class 的關係。我們可以在 Ruby Object 中找到什麼?</p><h4>六、Method lookup and constant lookup</h4><p>實驗模組 (Module) 與類別 Class 的關係，你將學到 Ruby 是怎麼在你的程式碼中找到 Method 和 Constant</p><h4>七、The Hash Table: the workhorse of Ruby internals</h4><p>探討 Ruby 在 Hash Table 的實作。當 Hash Table 出現時，MRI 在大量內部的 data 使用 hash table，不是只為了 Ruby 的 hash object</p><h4>八、How Ruby borrowed a decades-old idea from LISP</h4><p>揭露了 Ruby 大部分有用而且優雅的 feature，主要是建立於 LISP 的發展基礎上。</p><h4>九、Metaprogramming</h4><p>解決 Ruby 開發者其中一個很大的痛點，在了解 Ruby metaprogramming 之前，你會先學到如何使用它</p><h4>十、JRuby: Ruby on the JVM</h4><p>介紹 JRuby—用 Java 實作的 Ruby，你將會學到 JRuby 如何用 JVM 去有效地執行你的 Ruby 程式碼。</p><h4>十一、RUBINIUS: Ruby implemented with Ruby</h4><p>最有趣且有創意的其中一個實作，你將會學到如何修改 Rubinius 的 Ruby code，去看 Ruby method 是如何執行</p><h4><em>十二、Garbage collection in MRI, JRuby and RUBINIUS</em></h4><p>總結一下 GC，電腦科學內其中一門最神秘、最容易產生疑惑的課題。你將學到 Rubinius 和 JRuby 如何去使用來自 MRI 的演算法，去進行不同實作的 GC。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=601a1fbe7de7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ren-on-rails/ruby-under-a-microscope-601a1fbe7de7">推書 | Ruby Under a Microscope</a> was originally published in <a href="https://medium.com/ren-on-rails">Ryan on Ruby/Rails</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[推書 | Ruby Best Practice 讀後紀錄]]></title>
            <link>https://medium.com/ren-on-rails/ruby-best-practice-2-designing-beautiful-apis-%E7%AB%A0%E7%AF%80%E8%AE%80%E5%BE%8C%E7%B4%80%E9%8C%84-83e47205a801?source=rss----d14033a25b45---4</link>
            <guid isPermaLink="false">https://medium.com/p/83e47205a801</guid>
            <dc:creator><![CDATA[RYAN]]></dc:creator>
            <pubDate>Sun, 27 Nov 2016 13:51:37 GMT</pubDate>
            <atom:updated>2020-03-05T09:47:49.153Z</atom:updated>
            <content:encoded><![CDATA[<h3>Ch.2 Designing Beautiful APIs</h3><p>摘要</p><ul><li>Designing for Convenience: Ruport’s Table () feature</li><li>Ruby’s Secret Power: Flexible Argument Processing<br>- Standard Ordinal Arguments <strong>標準順序參數</strong><br>- Ordinal Arguments with Optional Parameters <strong>允許額外參數的順序參數</strong><br>- Psuedo-Keyword Arguments<br>- Treating Arguments As an Array <strong>將參數化為陣列</strong></li><li>Ruby’s Other Secret Power: Code Blocks<br>- Working with Enumerable<br>- Using Blocks to Abstract Pre- and Post-processing <strong>用 Block 來做前置與後置的處理</strong><br>- Blocks As Dynamic Callbacks <strong>動態呼叫的 Block</strong><br>- Blocks for Interface Simplification <strong>用 Block 簡化介面</strong></li><li>Avoiding Suprises<br>- Use attr_reader, attr_writer, and attr_accessor<br>- Understand What Method? and Method! Mean<br>- Make Use of Custom Operators</li><li>Conclusions</li></ul><h3>Designing for Convenience: Ruport’s Table () feature</h3><p>Ruport 其實就是 Ruby Report</p><p>在某些時候，幾乎所有的使用者都需要使用到表格化的數據，這些數據可能是任何數量，從簡單的 CSV 檔案到複雜的數據分析產生的表格都有可能。</p><p>提供一個適用於所有情境、簡單的 API，是個挑戰。</p><p>雖然不同情境要達成的最終目標是一樣的，但是實作的方式非常不同。我們的第一個本能，就是要反映出這一點：要實作能夠產生不同表格的構造函數。</p><pre>tabel1 = Ruport::Data::Table.new(<br>  :column_names =&gt; %w[first_name last_name]<br>  :data =&gt; [[&quot;Gregory&quot;, &quot;Brown&quot;], [&quot;Deborah&quot;, &quot;Orlando&quot;]]<br>)</pre><pre>table2 = Ruport::Data::Table.load(&quot;people.csv&quot;)</pre><pre>csv = &quot;first_name,last_name\nGregory,Brown\nDeborah,Orlando\n&quot;<br>table3 = Ruport::Data::Table.parse(csv)</pre><p>雖然上述的代碼範例，已經清楚表達每個地方在做什麼，但我們能仍需要記住名稱不同的 method。</p><p>我們可以用更好的方式去作：</p><pre>tabel1 = Table(%w[first_name last_name],<br>  :data =&gt; [[&quot;Gregory&quot;, &quot;Brown&quot;], [&quot;Deborah&quot;, &quot;Orlando&quot;]]<br>)</pre><pre>table2 = Table(&quot;people.csv&quot;)</pre><pre>csv = &quot;first_name,last_name\nGregory,Brown\nDeborah,Orlando\n&quot;<br>table3 = Table(:string =&gt; csv)</pre><p>不像是去初始化一個 Class，反而像是將 Data 轉換進 Table Object 裡面，這會比較像 Ruby 內建的一些方法：Ingeter(), Array() …etc</p><p>使用 Table() 去產生表格，是個非常棒的實作方法，它簡化了 Ruport 中許多常見的情境，不是破壞舊的接口而是選擇去包裝它。最明顯的一件事就是 Table () 就變成一個簡潔的代碼。</p><pre>def Table(*args, &amp;block)<br>  table = case args[0]<br>  when Array<br>    opts = args[1] || {}<br>    Ruport::Data::Table.new({:column_names =&gt; args[0]}.merge(opts), &amp;block)<br>  when /\.csv$/i<br>    Ruport::Data::Table.load(*args, &amp;block)<br>  when Hash<br>    if file = args[0].delete(:file)<br>      Ruport::Data::Table.load(file, args[0], &amp;block)<br>    elsif string = args[0].delete(:string)<br>      Ruport::Data::Table.parse(string, args[0], &amp;block)<br>    else<br>      Ruport::Data::Table.new(args[0], &amp;block)<br>    end<br>  else<br>    Ruport::Data::Table.new(:data =&gt; [], :columns =&gt; args, &amp;block)<br>  end<br>  return table<br>end</pre><p>雖然這個方法做了這麼多事情，讓人家看起來覺得「很忙」，但這個方法的目的是在於讓你可以「辨識」現在的表格是用哪個方法去產生。</p><p>適當的建構方法，是要將傳入的參數視為 Array，同時也能夠捕捉任何 Block 參數，以便將它傳進建構函數裡頭。</p><p>在第一個範例裡，我們已經使用 Hash 表示 options、Array 表示欄位名稱：</p><pre>tabel1 = Table(<br>　%w[first_name last_name],<br>　:data =&gt; [[&quot;Gregory&quot;, &quot;Brown&quot;], [&quot;Deborah&quot;, &quot;Orlando&quot;]]<br>)</pre><p>在這個情境，args 包含了兩個元素，一組 Array 的欄位名稱、一組 Hash 的選項，結構實際上是這樣：</p><pre>[ %w[first_name last_name],<br>  { :data =&gt; [[&quot;Gregory&quot;, &quot;Brown&quot;], [&quot;Deborah&quot;, &quot;Orlando&quot;]] } ]</pre><p>我們的 Case Statement 會比對 args[0] 是否為 Array，並且將 Hash 從 args[1] 拉出來。在處理完之後，最後一個呼叫會等於：</p><pre>Ruport::Data::Table.new(<br>  :column_names =&gt; %w[first_name last_name]<br>  :data =&gt; [[&quot;Gregory&quot;, &quot;Brown&quot;], [&quot;Deborah&quot;, &quot;Orlando&quot;]]<br>)</pre><p>就如同你看到的，看起來就是我們這個章節的第一個代碼範例，如果我們將 其中的 data 參數省略，將會變成：</p><pre>headings = %w[first_name last_name]<br>Ruport::Data::Table.new(<br>  :columns =&gt; headings) == Table(headings<br>) #=&gt; true</pre><p>第二個範例更簡單</p><pre>table2 = Table(&quot;people.csv&quot;)</pre><p>在這個情境，args 會是只有一個 element 的 Array，args[0] 會是 &quot;people.csv&quot;<br>我們的 case statement 會將它傳入 Ruport::Data::Table.load()。</p><p>在這個情境，我們的 Table() 會呼叫 Ruport::Data::Table.load() 只要你的檔案是 .csv 結尾。</p><p>但如果你的檔案，有可能不是標準的副檔名怎麼辦？Table () 必須做更多的事情來處理它。</p><pre>Table(:file =&gt; &quot;people.txt&quot;)</pre><p>在這個例子下，args 是只有一個為 Hash 的元素的 Array，這個例子有點不夠曖昧，因為我們的第三個例子也符合這條件：</p><pre>csv = &quot;first_name,last_name\nGregory,Brown\nDeborah,Orlando\n&quot;<br>table3 = Ruport::Data::Table.parse(csv)</pre><p>即使它還沒出現，Table () 仍然必須要用 Ruport::Data::Table.new() 提供一個能夠相容的介面，表示底下這個範例也必須有效：</p><pre>table4 = Table(:column_names =&gt; %w[first_name, last_name],<br>  :data =&gt; [[&quot;Gregory&quot;, &quot;Brown&quot;], [&quot;Deborah&quot;, &quot;Orlando&quot;]] )</pre><p>那三個不同的情境，能夠輕易的被辨識，就像你能看到的：</p><pre>if file = args[0].delete(:file)<br>  Ruport::Data::Table.load(file, args[0], &amp;block)<br>elsif string = args[0].delete(:string)<br>  Ruport::Data::Table.parse(string, args[0], &amp;block)<br>else<br>  Ruport::Data::Table.new(args[0], &amp;block)<br>end</pre><p>這個代碼，嘗試在被執行到對應的建構函數以前，從 options 來刪除 :file 或 :string 選項，這是個很棒的實作，在將 options Hash 繼續往下傳以前，避免建構函數無法處理傳過去的參數。</p><pre>// 將第一個名字不是 Gregory 的紀錄刪除<br>table = Table(&quot;foo.csv&quot;) do |t,r|<br>  t.filter { |r| r.first_name == &quot;Gregory&quot; }<br>  t &lt;&lt; r<br>end</pre><pre>// 將第一個欄位的值變成雙倍<br>table = Table(&quot;a&quot;, &quot;b&quot;, &quot;c&quot;) do |t|<br>  t.transform { |r| r[&quot;a&quot;] *= 2 }<br>  t &lt;&lt; [1, 2, 3]<br>  t &lt;&lt; [4, 5, 6]<br>end</pre><p>第一個例子是 Iterator，遍歷所有 CSV 的欄位。<br>第二個例子，能夠讓使用者自由的加入內容到自己的表格中。</p><p>上述兩個用法，都是在顯示使用 Block 的好處。</p><p>但目前 Table() 使用的方法，都只能在特定領域中使用，接下來要使用一些 Ruby 提供的基本方法，讓你能夠去應付不同的接口。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83e47205a801" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ren-on-rails/ruby-best-practice-2-designing-beautiful-apis-%E7%AB%A0%E7%AF%80%E8%AE%80%E5%BE%8C%E7%B4%80%E9%8C%84-83e47205a801">推書 | Ruby Best Practice 讀後紀錄</a> was originally published in <a href="https://medium.com/ren-on-rails">Ryan on Ruby/Rails</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ruby — 使用 copy 或 dup 複製 Object]]></title>
            <link>https://medium.com/ren-on-rails/ruby-%E4%BD%BF%E7%94%A8-copy-%E6%88%96-dup-%E8%A4%87%E8%A3%BD-object-2d2101646fbe?source=rss----d14033a25b45---4</link>
            <guid isPermaLink="false">https://medium.com/p/2d2101646fbe</guid>
            <dc:creator><![CDATA[RYAN]]></dc:creator>
            <pubDate>Sat, 05 Nov 2016 09:29:49 GMT</pubDate>
            <atom:updated>2016-11-05T09:29:49.538Z</atom:updated>
            <content:encoded><![CDATA[<h3>.copy 與 .dup</h3><p>都可以用來複製一個 object，都是淺拷貝，都會複製 “frozen”、”tainted” 兩種狀態。</p><p>clone 會連方法一起複製，但 dup 卻不會。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d2101646fbe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ren-on-rails/ruby-%E4%BD%BF%E7%94%A8-copy-%E6%88%96-dup-%E8%A4%87%E8%A3%BD-object-2d2101646fbe">Ruby — 使用 copy 或 dup 複製 Object</a> was originally published in <a href="https://medium.com/ren-on-rails">Ryan on Ruby/Rails</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ruby — Array 操作速讀]]></title>
            <link>https://medium.com/ren-on-rails/ruby-array-%E6%93%8D%E4%BD%9C%E9%80%9F%E8%AE%80-9647b4ff0a6b?source=rss----d14033a25b45---4</link>
            <guid isPermaLink="false">https://medium.com/p/9647b4ff0a6b</guid>
            <dc:creator><![CDATA[RYAN]]></dc:creator>
            <pubDate>Sat, 05 Nov 2016 09:11:37 GMT</pubDate>
            <atom:updated>2016-12-27T01:56:46.373Z</atom:updated>
            <content:encoded><![CDATA[<pre>a = [1, 2]<br>b = [3, 4]</pre><h3>將多個 Array 串接為一個 Array</h3><pre>a + b<br>a.concat b</pre><pre>c = [1, 2, 3, 4]</pre><h3>為 Array 新增一個 Element</h3><pre>## 新增在 Array 的後方</pre><pre>a &lt;&lt; b<br>a.push b</pre><pre>c = [1, 2, [3, 4]]</pre><pre>## 新增在 Array 的前方</pre><pre>a.unshift b</pre><pre>c = [[3, 4], 1, 2]</pre><h3><strong>Array 的迭代 (Iteration)</strong></h3><h4>基本款 .each</h4><pre>[1, 2, 3].each { |elem| puts elem }<br>&gt; 1<br>&gt; 2<br>&gt; 3</pre><h4>推薦款 .map</h4><p>會將每個元素在 Block 內計算的結果，在最後組成一個 Array 並回傳。</p><pre>[1, 2, 3].map { |elem| elem*elem }<br>&gt; [1, 4, 9]</pre><h4>推薦款 .reduce（ .inject）</h4><p>可以給予初始值，去作迭代。</p><pre>## 第一個參數：初始值<br>## 第二個參數：執行的方法、Block</pre><pre>[1, 2, 3].reduce(0) { |total, elem| total += elem }<br>&gt; 6</pre><pre>[1, 2, 3].reduce(0, :+)<br>&gt; 6</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9647b4ff0a6b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ren-on-rails/ruby-array-%E6%93%8D%E4%BD%9C%E9%80%9F%E8%AE%80-9647b4ff0a6b">Ruby — Array 操作速讀</a> was originally published in <a href="https://medium.com/ren-on-rails">Ryan on Ruby/Rails</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mongoid — find 與 where 的差別]]></title>
            <link>https://medium.com/ren-on-rails/mongoid-find-%E8%88%87-where-%E7%9A%84%E5%B7%AE%E5%88%A5-24e6c4eeeb6e?source=rss----d14033a25b45---4</link>
            <guid isPermaLink="false">https://medium.com/p/24e6c4eeeb6e</guid>
            <dc:creator><![CDATA[RYAN]]></dc:creator>
            <pubDate>Sat, 05 Nov 2016 08:58:35 GMT</pubDate>
            <atom:updated>2016-11-05T08:57:39.086Z</atom:updated>
            <content:encoded><![CDATA[<h3>Reference</h3><p><a href="https://ruby-china.org/topics/1157">Mongoid: find 和 where 有哪些区别？ · Ruby China</a></p><h3>Model.find</h3><p>參數可以接受：</p><ol><li>id</li><li>id Array</li></ol><p>如果<strong>找不到任何 record，會報錯。</strong></p><h3>Model.where</h3><p>如果<strong>找不到任何 record，不會報錯</strong>，會返回空紀錄。</p><p>where 使用的是延遲查詢，意思是它所返回的物件為 Mongoid::Criteria、ActiveModel::Relations ; 它儲存了我們所執行的「查詢條件」，並沒有在 DB 真的執行，只有在我們真的要使用這些 data（如：在 view print 出來）才會真的執行。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=24e6c4eeeb6e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ren-on-rails/mongoid-find-%E8%88%87-where-%E7%9A%84%E5%B7%AE%E5%88%A5-24e6c4eeeb6e">Mongoid — find 與 where 的差別</a> was originally published in <a href="https://medium.com/ren-on-rails">Ryan on Ruby/Rails</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Active Record — Eager Loading]]></title>
            <link>https://medium.com/ren-on-rails/active-record-eager-loading-1c2aaba1d2f3?source=rss----d14033a25b45---4</link>
            <guid isPermaLink="false">https://medium.com/p/1c2aaba1d2f3</guid>
            <dc:creator><![CDATA[RYAN]]></dc:creator>
            <pubDate>Sat, 05 Nov 2016 08:43:28 GMT</pubDate>
            <atom:updated>2016-11-05T08:44:47.444Z</atom:updated>
            <content:encoded><![CDATA[<h3>Reference</h3><p><a href="http://rails.ruby.tw/active_record_querying.html#eager-loading-%E9%97%9C%E8%81%AF">http://rails.ruby.tw/active_record_querying.html#eager-loading-%E9%97%<br>9C%E8%81%AF</a></p><h3>What is Eager Loading?</h3><p>一種用來解決 N+1 Query 問題的方式。</p><p>以 Active Record 為例：</p><pre>customers = Customer.limit(10)</pre><pre>customers.each do |customer|<br>  puts customer.info.phone<br>end</pre><p>上述程式碼沒有錯誤，但<strong>總共執行了 11 次 query</strong>。</p><p>第一次拿到全部的 Customer，在 iterate 10 次去拿每個 customer 的 phone</p><h3>How to implement?</h3><p>在 Active Record 裡頭，使用 Model.find 搭配 includes，可以預先載入該 Model 指定的關聯（Relation）。</p><pre>customers = Customer.includes(:info).limit(10)</pre><pre>customers.each do |customer|<br>  puts customer.info.phone<br>end</pre><p>query 次數便從 11 次下降為 2 次。</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c2aaba1d2f3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ren-on-rails/active-record-eager-loading-1c2aaba1d2f3">Active Record — Eager Loading</a> was originally published in <a href="https://medium.com/ren-on-rails">Ryan on Ruby/Rails</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Active Record 簡單說]]></title>
            <link>https://medium.com/ren-on-rails/active-record-%E7%B0%A1%E5%96%AE%E8%AA%AA-902c08a5e0bc?source=rss----d14033a25b45---4</link>
            <guid isPermaLink="false">https://medium.com/p/902c08a5e0bc</guid>
            <dc:creator><![CDATA[RYAN]]></dc:creator>
            <pubDate>Sun, 10 Apr 2016 09:58:36 GMT</pubDate>
            <atom:updated>2016-04-10T09:59:04.732Z</atom:updated>
            <content:encoded><![CDATA[<h3>參考資料</h3><p><a href="http://rails.ruby.tw/active_record_querying.html">http://rails.ruby.tw/active_record_querying.html</a></p><h3>Active Record 是什麼？</h3><p>它可以幫你做資料庫的查詢，而且相容大部分的資料庫 ; 讓你輕鬆使用 Active Record 的方法就能操作資料庫，不需要直接去寫直接的 SQL 指令。</p><h3>Active Record 能幫你做什麼？</h3><ol><li>取出資料：使用 AR 提供的多種 finder 對資料庫做查詢。</li><li>條件：使用 where 方法去取出符合條件的紀錄。</li><li>排序：按照特定順序來取出紀錄。</li><li>選出特定欄位</li><li>Limit 與 Offset</li><li>Group</li><li>Having</li><li>覆蓋條件</li><li>空的 Relation</li><li>唯讀物件：禁止修改回傳的物件 (紀錄)。</li><li>更新時，鎖定紀錄：避免 race condition</li><li>連接資料表</li><li>Eager Loading</li><li>作用域：可以將常用的查詢定義成一個物件或 Model 的方法。</li><li>動態查詢</li><li>尋找或新建物件：在找不到紀錄的時候，新建一個物件。</li><li>用 SQL 查詢</li><li>物件存在性</li><li>計算</li><li>執行 Explain</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=902c08a5e0bc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ren-on-rails/active-record-%E7%B0%A1%E5%96%AE%E8%AA%AA-902c08a5e0bc">Active Record 簡單說</a> was originally published in <a href="https://medium.com/ren-on-rails">Ryan on Ruby/Rails</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[在 Rails 上使用 Elastic Search]]></title>
            <link>https://medium.com/ren-on-rails/elasticsearch-in-ror-b0142a93fcb7?source=rss----d14033a25b45---4</link>
            <guid isPermaLink="false">https://medium.com/p/b0142a93fcb7</guid>
            <dc:creator><![CDATA[RYAN]]></dc:creator>
            <pubDate>Sun, 27 Mar 2016 16:28:14 GMT</pubDate>
            <atom:updated>2016-04-10T10:00:17.860Z</atom:updated>
            <content:encoded><![CDATA[<h3>Source</h3><ul><li><a href="http://es.xiaoleilu.com/010_Intro/05_What_is_it.html">是什么| Elasticsearch权威指南</a></li><li><a href="http://www.learnes.net/">Gitbook — ElasticSearch 权威指南</a></li><li><a href="https://ruby-china.org/topics/15337">Ruby China — ElasticSearch 初次使用小结，一起学习进步哈~</a></li><li><a href="https://ruby-china.org/topics/27530">Ruby China — 整合 ElasticSearch 到现有 Rails 项目</a></li></ul><h3>Features</h3><ol><li>Open source</li><li>Apache Lucene</li><li>Schema free</li><li>Document Oriented</li><li>Realtime Data &amp; Analytics</li><li>Distributed</li><li>High availability</li><li>RESTful API / JSON format / multi-tenancy / Full-text search / Conflict management / per-operation persistence</li></ol><h3>How to implement?</h3><blockquote>Gemfile</blockquote><pre>gem &#39;elasticsearch-rails&#39;<br>gem &#39;elasticsearch-model&#39;</pre><blockquote>Model</blockquote><pre># 在 Model 裡 include 模組之後，就可以使用 ES 的「搜尋」功能了。<br>include Elasticsearch::Model<br>include Elasticsearch::Model::Callbacks</pre><pre># 透過傳入的參數，讓 ES 去進行搜尋<br>def self.search ( search )<br>  response = __elasticsearch__.search( search )<br>end</pre><pre># 透過 DSL 能夠更精準去搜尋。<br>def self.search_filter ( params )<br>  response = __elasticsearch__.search(<br>    &quot;query&quot;: {<br>      &quot;filtered&quot;: {<br>        &quot;filter&quot;: {<br>          &quot;bool&quot;: {<br>            &quot;must&quot;: { &quot;term&quot;: { &quot;status&quot;: &quot;1&quot; } },<br>                      &quot;must&quot;: { &quot;query&quot;: {<br>                                &quot;match&quot;: { &quot;name&quot;: params }<br>                              }<br>                    }<br>                  }<br>                  }<br>                  }<br>             }<br>  )<br>end</pre><h3>使用 ES 之前，必須先做兩件事</h3><p>一、在使用 ES 之前，必須先幫 Model 建立 index（供 ES 使用）</p><pre># 方式一<br>mapping dynamic: false do<br>  indexes :name<br>  indexes :tag<br>end</pre><pre># 方式二：將 model 序列化<br># only 是欄位<br># include 處理 association<br>def as_indexed_json (options = {})<br>  self.as_json(<br>    only: [:id, :name, :description, :status],<br>    include: { tags: { only: [ :name ] }}<br>  )<br>end</pre><p>二、單單建立 index，還是無法使用 ES 的，必須要將 Data 輸入 ES</p><pre># 方式一<br>$ Model.import</pre><pre># 方式二<br>$ rake environment elasticsearch:model:import CLASS=‘model-name’ FORCE=y</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b0142a93fcb7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ren-on-rails/elasticsearch-in-ror-b0142a93fcb7">在 Rails 上使用 Elastic Search</a> was originally published in <a href="https://medium.com/ren-on-rails">Ryan on Ruby/Rails</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[譯] How DHH organize his Rails Controllers]]></title>
            <link>https://medium.com/ren-on-rails/how-dhh-organize-his-rails-controllers-%E8%AD%AF-%E5%BF%AB%E9%80%9F%E7%AD%86%E8%A8%98-74323db694c5?source=rss----d14033a25b45---4</link>
            <guid isPermaLink="false">https://medium.com/p/74323db694c5</guid>
            <dc:creator><![CDATA[RYAN]]></dc:creator>
            <pubDate>Sun, 20 Mar 2016 06:13:53 GMT</pubDate>
            <atom:updated>2019-01-14T07:15:53.569Z</atom:updated>
            <content:encoded><![CDATA[<p>source: <a href="http://jeromedalbert.com/how-dhh-organizes-his-rails-controllers/">http://jeromedalbert.com/how-dhh-organizes-his-rails-controllers/</a></p><h3>加入非預設的 REST 動作</h3><p>假設你有個 InboxController，其中有個 index method 去顯示在 inbox 的每樣東西 ; 另外你可能還想要看到 pendin 的 emails 或諸如此類的東西，你需要加入 pendings 的 method:</p><pre>class InboxesController &lt; ApplicationController<br>  def index<br>  end</pre><pre>  def pendings<br>  end<br>end</pre><p>是個非常常見的 Pattern 吧？是個我曾經最常用的 pattern</p><p>但現在，我會說「不、不、不」</p><p>應該要有個新的 controller 叫 Inboxes::PendingsController，然後只有一個 method 叫做 index</p><pre>Class InboxesController &lt; ApplicationController<br>  def index<br>  end<br>end</pre><pre>Class Inboxes::PendingsController &lt; ApplicationController<br>  def index<br>  end<br>end</pre><p>我所發現的是，這樣做會讓你有足夠自由的空間，讓每個 Controller 擁有自己的 Scope 去加入參數使用 Filter.</p><p>因此，每個 Controller 能夠擁有自己的 namespace 去做擴充。<br>舉個例：我們有個 MessagesController，在它底下我們可能會有 Messages::DraftsController、Messages::TrashesController 或其他相似的 sub-controller，這是個非常棒的應用。</p><p>所以，基本上 Controller 應該只使用到預設的 CRUD 動作（index、show、new、edit、create、update、destroy），其他的動作都應該要再創造一個 Controller（並且擁有它自己的 CRUD）</p><h3>Jerome 的看法</h3><p>DHH 提到的例子只有關於 Filter，可能會過度影響到其他簡單的 controller 動作邏輯，舉例來說，在 REST 最常見的實作 filter 的做法是使用 query parameters（e.g. GET /inboxes?state=pending），正常來說，我都會使用剛剛說的做法，但如果邏輯太多、太複雜，我會推薦使用 DHH 的做法。</p><p>我完全支持將 Controller 拆開的做法，有幾個理由：</p><blockquote><strong>驅使你寫出更簡單的 code</strong></blockquote><p>你必須要自己做判斷：如果 Controller 只有預設的 CRUD 動作，可能不需要將 index/show 拆去各自所屬的 Controller</p><p>如果 Controller 變得越來越肥，雖然它只有基本的 CRUD 動作，還是將那些 code 放到它專用的 Controller，舉例來說（透過 API 去購買商品）：</p><pre>class Api::V1::PurchashesController &lt; Api::V1::ApplicationController</pre><pre>  rescue_form stripe::stripeError, with: :log_payment_error</pre><pre>  def create<br>    load_product<br>    load_device<br>    load_or_create_user</pre><pre>    create_order<br>    create_payment<br>    authorize_payment<br>    confirm_address</pre><pre>    render json: @order, status: :created<br>  end</pre><pre>  private</pre><pre>  def load_product<br>    @product = Product.find_by!(uuid: params[:product_id])<br>  end</pre><pre>  ...</pre><pre>end</pre><p>這裏只有一個預設的 CRUD create 動作，在肥肥的 module 中沒有預先的抽象化，沒有 service classes、沒有 observers，沒有任何東西。所有東西都完美的包在這支 Controller，不需要跳好幾個檔案去看 code，因為所有的 entry point 都在這支 Controller.</p><p>“Duplication is far cheaper than the wrong abstraction.”</p><blockquote>讓你的 Code 更直覺</blockquote><p>只有 CRUD 動作的 Controller 很酷！不需要猜測、不需要探勘挖掘、不需要無窮的瀏覽去找一個奇怪的動作。不需要懷疑是不是有一個自訂的 controller 對應到另外的 route.</p><p>我不喜歡作平乏無味的組織化，我喜歡直覺的 code，在 confuguration 上嚴謹的規範，是我在這麼多 Ruby 框架中喜歡 Rails 的理由。每樣事物都用同樣的方式去組織，你可以花更少的時間去決定如何實作。</p><p>理論上，它代表的是你可以在很短的時間內，從一個 Codebase 轉移到另外一個。但事實上，可能會遇到很多可怕的 Rails application. 某間公司可能會在架構上使用 observers pattern，另一間可能使用 Traiblazer，在另外一間使用另外一種，等等等…</p><p>都是因為他們使用了所謂的 lack of structure 的 vanilla Rails app，所以他們才要尋找額外的 structure，但最簡單的 solution 就在眼前，將你的 Controller 拆了，然後只使用基本的 CRUD 動作，非常簡單，而且對 Junior 的開發者友善。</p><p>對於不自在、不簡單的實作，拆了 Controller 是個非常棒的 solution。</p><blockquote>讓你在 REST 的條件下做思考</blockquote><p>很多人喜歡 REST 是因為它很直覺、很簡單，一旦你了解 REST，你很容易了解更多東西。</p><p>在不同 App 上的商業邏輯可能會不同：<br>- create a charge in Strip<br>- create a SMS in Twilio<br>- get a repository in Github<br>…</p><p>你必須讓自己透過 REST 去思考，而不是透過「行為」：<br>- 你不需要「pay」，你需要「create a pay」<br>- 你不需要「add funds to your balance」，你需要「create a fund in a balance」</p><p>透過 REST 可以讓商業邏輯更清楚、更簡潔，你可以使用少少的物件做到更多的事情。</p><p>舉個例子：<br>（RESTful 的 Rails 路由，對應被拆解過只用 CRUD 動作的 Contoller）</p><pre>resources :purchases, only: :create</pre><pre>resources :cost_calculations, only: :create</pre><pre>namespace :company do<br>  resources :account_details, only: :update<br>  resources :websites_details, only: :update<br>  resources :contact_details, only: :update<br>end</pre><pre>namespace :balance do<br>  resources :funds, only: :create<br>end</pre><pre>resource :bank_account, only: :create</pre><p>針對那些 REST 設計（尤其是擁有很多 sub-sources 的），我通常都會先在筆記上寫下來 REST action+resource（例如：POST /balance/funds），不需要擔心任何實作，然後在我想到比較好的命名後，我才會將它轉換成 Rails 的路由，因為 Rails 有相當棒的資源去支援 REST</p><h3>總結</h3><p>如果 Controller 有特定的 scope、太多 logic、太多可能產生副作用的疑慮，那就拆解它吧！</p><p>但這不表示你不需要使用「抽象化」，終究會遇到的。</p><p>有些時候，很多個 Controller 需要使用同樣的 logic。<br>有些時候，某個被拆開的、只擁有一個 public method 的 Controller，可能還是很胖，這時候就需要考慮使用 model methods 或者 services objects（如果你小心點，可能可以使用少少的 services object 去達成目的）</p><p><strong>「當你的 app 長越大，你必須要花更多時間去了解它，不論 Code 有多 clean。但是拆解 Controller 可以讓事情變得更簡單。」</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74323db694c5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ren-on-rails/how-dhh-organize-his-rails-controllers-%E8%AD%AF-%E5%BF%AB%E9%80%9F%E7%AD%86%E8%A8%98-74323db694c5">[譯] How DHH organize his Rails Controllers</a> was originally published in <a href="https://medium.com/ren-on-rails">Ryan on Ruby/Rails</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Basic Ruby [ 02 / 02 ] (待完成)]]></title>
            <link>https://medium.com/ren-on-rails/basic-ruby-02-02-2ccecf563958?source=rss----d14033a25b45---4</link>
            <guid isPermaLink="false">https://medium.com/p/2ccecf563958</guid>
            <dc:creator><![CDATA[RYAN]]></dc:creator>
            <pubDate>Sun, 20 Mar 2016 06:11:31 GMT</pubDate>
            <atom:updated>2019-11-04T16:20:32.910Z</atom:updated>
            <content:encoded><![CDATA[<p>本篇是看<a href="https://www.codeschool.com/courses/ruby-bits-part-2">《Ruby bits 2》 — Code School </a>教學影片的快速筆記。</p><p>上集傳送門：<a href="https://medium.com/ren-on-rails/basic-ruby-01-02-840c3ad56f79#.xhu15fttb">Basic Ruby [ 01 / 02]</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ccecf563958" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ren-on-rails/basic-ruby-02-02-2ccecf563958">Basic Ruby [ 02 / 02 ] (待完成)</a> was originally published in <a href="https://medium.com/ren-on-rails">Ryan on Ruby/Rails</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>