<?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 Andrew Livingston on Medium]]></title>
        <description><![CDATA[Stories by Andrew Livingston on Medium]]></description>
        <link>https://medium.com/@amliving?source=rss-dac127fbd53------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Ymhk_gjwB28QiNwJ19X0mQ.jpeg</url>
            <title>Stories by Andrew Livingston on Medium</title>
            <link>https://medium.com/@amliving?source=rss-dac127fbd53------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 05:01:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amliving/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[Setting up Rspec]]></title>
            <link>https://medium.com/@amliving/my-rails-rspec-set-up-6451269847f9?source=rss-dac127fbd53------2</link>
            <guid isPermaLink="false">https://medium.com/p/6451269847f9</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[rspec]]></category>
            <dc:creator><![CDATA[Andrew Livingston]]></dc:creator>
            <pubDate>Tue, 06 Feb 2018 02:26:03 GMT</pubDate>
            <atom:updated>2018-04-25T18:22:17.701Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, I’d like to record for willing readers and my future-self how I go about configuring Rspec for writing tests in Rails. This will not be a tutorial on how to write tests, why to write tests or what kinds of tests to write, but rather a nuts and bolts reference for adding Rspec-driven testing tooling to a Rails project. There’s a lot of noise out there in the testing world, so I’ll try to make this post to-the-point.</p><h4>Step 1 — Delete Any Existing Test Folders</h4><p>If I’ve generated a new rails app using rails new &lt;app&gt; without using any additional flags, I remove the app/test directory:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A1nBYg6B16NC0JCutVTw9g.png" /></figure><h4>Step 2 — Add Gems</h4><p>I add the following gems to the :development, :test group in my Gemfile and run bundle.</p><pre>group :development, :test do<br>  gem &#39;byebug&#39;, platform: :mri<br>  gem &#39;rspec-rails&#39;, &#39;~&gt; 3.5&#39;<br>  gem &#39;factory_girl_rails&#39;<br>  gem &#39;capybara&#39;<br>  gem &#39;database_cleaner&#39;<br>end</pre><p>Briefly running through these gems one-by-one:</p><ol><li>byebug allows for step-through debugging by placing byebug anywhere in the app.</li><li>rspec-rails is the testing framework.</li><li>factory_girl_rails replaces Rails fixtures for generating data to use in the tests.</li><li>capybara provides helper methods that make integration testing easier.</li><li>database_cleaner allows us to manage our testing database with precision: we decide when to wipe data (e.g. after, before tests).</li></ol><h4><strong>Step 3 — Run Rspec Generator</strong></h4><p>Currently, the app directory doesn’t include a app/test/ directory (remember we deleted it in step 1), so I have nowhere to put my tests. This is where the Rspec generator, which will generate app/spec/, comes in:</p><pre>rails generate rspec:install</pre><p>This adds the following files in a app/spec directory:</p><ul><li>spec/spec_helper.rb</li><li>spec/rails_helper.rb</li></ul><p>and app/.rspec in the project’s root directory.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3LCQg9WtVoYObYLRWHghBA.png" /></figure><p>Now I’ve added the proper files to use Rspec instead of Minitest::Unit, but I still need to do a little more configuration before Rspec will work with the factory_girl_rails, capybara, and database_cleaner gems.</p><h4>Step 4 — Configure Rspec</h4><p>Open up spec/rails_helper.rb. All of the instructions from this section will be implemented in this file. I include the complete rails_helper.rb file at the bottom of this section.</p><p><strong>database_cleaner</strong></p><p>To use database_cleaner, I add require &#39;database_cleaner&#39; below require &#39;rspec/rails&#39;, and change the following line in the Rspec.configure bloc from</p><pre>config.use_transactional_fixtures = true</pre><p>to</p><pre>config.use_transactional_fixtures = false</pre><p>Then I add the following to the Rspec.configure block:</p><pre>RSpec.configure do |config|</pre><pre>  #...omitted code...</pre><pre>  config.use_transactional_fixtures = false</pre><pre>  config.before(:suite) do<br>    DatabaseCleaner.clean_with(:truncation)<br>  end</pre><pre>  config.before(:each) do<br>    DatabaseCleaner.strategy = :transaction<br>  end</pre><pre>  config.before(:each, :js =&gt; true) do<br>    DatabaseCleaner.strategy = :truncation<br>  end</pre><pre>  config.before(:each) do<br>    DatabaseCleaner.start<br>  end</pre><pre>  config.after(:each) do<br>    DatabaseCleaner.clean<br>  end</pre><pre>  config.before(:all) do<br>    DatabaseCleaner.start<br>  end</pre><pre>  config.after(:all) do<br>    DatabaseCleaner.clean<br>  end</pre><pre> #...omitted code...<br> <br>end</pre><p><strong>capybara</strong></p><p>To use capybara, I add require &#39;capybara/rspec&#39; after require &#39;rspec/rails&#39;.</p><p><strong>factory_girl_rails</strong></p><p>To use factory_girl_rails, I remove this line:</p><pre>config.fixture_path = &quot;#{::Rails.root}/spec/fixtures&quot;</pre><p>And add to the Rspec.configure block:</p><pre>config.include FactoryGirl::Syntax::Methods</pre><p>This will give me access to FactoryGirl methods like build and create. I place all of my factories in the spec/factories directory.</p><p><strong>devise</strong></p><p>If my app uses devise for authentication, I add:</p><pre>config.include Devise::Test::ControllerHelpers, type: :controller</pre><p>to the Rspec.configure block. This gives me helper methods like sign_in.</p><p><strong>miscellaneous pointers</strong></p><p>At the bottom of Rspec.configure block, you’ll see the following line:</p><pre>config.infer_spec_type_from_file_location!</pre><p>This allows rails to infer from the location of the spec file what kind of test it is and then give you context-specific helper methods (e.g. using get and post in controller tests if the file is found in the spec/controllers directory).</p><p>My complete rails_helper.rb file looks like this:</p><pre>ENV[&#39;RAILS_ENV&#39;] ||= &#39;test&#39;</pre><pre>require &#39;spec_helper&#39;<br>require File.expand_path(&#39;../../config/environment&#39;, __FILE__)<br>require &#39;rspec/rails&#39;<br>require &#39;database_cleaner&#39;<br>require &#39;capybara/rspec&#39;</pre><pre>Dir[Rails.root.join(&#39;spec/support/**/*.rb&#39;)].each { |f| require f }<br>ActiveRecord::Migration.maintain_test_schema!</pre><pre>RSpec.configure do |config|<br>  config.use_transactional_fixtures = false<br>  config.include FactoryGirl::Syntax::Methods<br>  config.include Devise::Test::ControllerHelpers, type: :controller<br>  config.before(:suite) do<br>    DatabaseCleaner.clean_with(:truncation)<br>  end<br>  config.before(:each) do<br>    DatabaseCleaner.strategy = :transaction<br>  end<br>  config.before(:each, js: true) do<br>    DatabaseCleaner.strategy = :truncation<br>  end<br>  config.before(:each) do<br>    DatabaseCleaner.start<br>  end<br>  config.after(:each) do<br>    DatabaseCleaner.clean<br>  end<br>  config.before(:all) do<br>    DatabaseCleaner.start<br>  end<br>  config.after(:all) do<br>    DatabaseCleaner.clean<br>  end<br>  config.infer_spec_type_from_file_location!<br>end</pre><h4>Step 5 — Write Tests</h4><p>Now I’m ready to write some tests, all of which reside in the spec directory. Typically my spec directory looks something like this:</p><pre>spec/<br>  controllers/<br>    user_controller_spec.rb<br>    resource_controller_spec.rb<br>  factories/<br>    user.rb<br>    resource.rb<br>  models/<br>    user_spec.rb<br>    resource_spec.rb<br>  mailers/<br>    mailer_spec.rb<br>  services/<br>    service_spec.rb  <br>  rails_helper.rb<br>  spec_helper.rb</pre><p>This is by no means an exhaustive summary of all the different gems and tools that one can use in tests, but it does record my simple set up for getting going quickly. I hope it was useful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6451269847f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails DB Lesson Learned]]></title>
            <link>https://medium.com/@amliving/rails-db-lesson-learned-e416e2f2549c?source=rss-dac127fbd53------2</link>
            <guid isPermaLink="false">https://medium.com/p/e416e2f2549c</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[postgres]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Andrew Livingston]]></dc:creator>
            <pubDate>Fri, 10 Mar 2017 02:16:24 GMT</pubDate>
            <atom:updated>2017-03-10T02:16:24.174Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using PostgreSQL in production? Use it in development too.</h4><p>If you’ve ever had a demo fail in public or haven’t and hope to avoid it, learn a lesson from me: use the same RDBMS in development and production.</p><p>A standard new rails app ships with SQLite for the development database. It works great out of the box; there’s no set-up required, you generate some migrations, type rake db:migrate, and you’re good to go. And then when you deploy the app to Heroku or elsewhere for production, you use PostgreSQL, and everything, again seems to work like magic.</p><p>However, there are differences between SQLite and PostgreSQL that might come back to haunt you if you’re not careful. I learned the hard way that SQLite and PostgreSQL treat null values differently when ordering by column. For example, when ordering by a column, PostgreSQL orders rows with null at the bottom of the ordering, while SQLite orders rows with null values at the top of the ordering.</p><p>A quick example from a project mine. I’m building an app that allows speakers to send questions to their audiences. For various reasons, I needed to select to last question sent, based on a sent_at column of type datetime in the questions table. I was selecting the last question sent during a particular lecture with a query like this:</p><pre>lecture.questions.order(:sent_at).last</pre><p>However, there were some questions that contained null values in the sent_at column. In development with SQLite, the rows containing null values in the sent_at column were ordered <em>before </em>the oldest questions, so calling</p><pre>lecture.questions.order(:sent_at).last</pre><p>gave me the row I was looking for.</p><p>However, in PostgreSQL the rows containing null values in the sent_at column were ordered <em>after </em>the most recent questions, so calling the query above gave me a question with a null value in the sent_at column, which was <em>not </em>the entry I was looking for.</p><p>This oversight caused the app to break in a public test. But it taught me two important lessons:</p><ol><li>Be conscientious in your database design. Always think about edge cases that could yield unexpected query results. In this case, I needed to correctly handle null values in the sent_at column of the questions_table.</li><li>Use the same RDBMS in production and development. If you’re using PostgreSQL in production, use it in development. That way, you are less likely to be surprised by slightly different behaviors among SQL implementations after you push to production. Practice like you’re performing.</li></ol><p>Thanks for reading — I hope this helps!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e416e2f2549c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Diving Into Ruby’s attr_accessor]]></title>
            <link>https://medium.com/@amliving/diving-into-rubys-attr-accessor-d34e2ccc5477?source=rss-dac127fbd53------2</link>
            <guid isPermaLink="false">https://medium.com/p/d34e2ccc5477</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[metaprogramming]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[Andrew Livingston]]></dc:creator>
            <pubDate>Wed, 08 Mar 2017 18:54:51 GMT</pubDate>
            <atom:updated>2019-05-20T18:28:04.673Z</atom:updated>
            <content:encoded><![CDATA[<h4>accessorizing ruby</h4><p>In this post, I hope to use a recreation of attr_accessor as an entry point into some interesting features of Ruby, including:</p><ol><li>Ruby’s object model</li><li>Metaprogramming (by way of define_method)</li><li>class not as a definition, but as an expression that is evaluated</li></ol><p>Let’s get started!</p><h4><strong>It’s Not Magic</strong></h4><p>We all know Ruby’s attr_accessor as a magical way to get and set instance variables. For example, in</p><pre>class MyClass<br>  attr_accessor :variable_one, :variable_two</pre><pre>  def initialize(param_one, param_two)<br>    self.variable_one = param_one<br>    self.variable_two = param_two<br>  end<br>end</pre><pre>new_instance = MyClass.new(&quot;one&quot;, &quot;two&quot;)</pre><pre>new_instance.variable_one = &quot;new string&quot;</pre><pre>new_instance.variable_one<br># =&gt; &quot;new string&quot;</pre><pre>new_instance.variable_two<br># =&gt; &quot;two&quot;</pre><p>attr_accessor allows us to get and set the instance variables @variable_one, and @variable_two from outside the class.</p><p>But what exactly is happening here? Because we’re able to call variable_one and variable_two as methods on an instance of MyClass, somehow attr_accessor is creating public methods for us. We can verify this:</p><pre>class MyClass<br>  attr_accessor :variable_one, :variable_two</pre><pre>  def initialize(param_one, param_two)<br>    @variable_one = param_one<br>    @variable_two = param_two<br>  end<br>end</pre><pre>new_instance = MyClass.new(&quot;one&quot;, &quot;two&quot;)</pre><pre>new_instance.public_methods<br># =&gt; [:variable_one, :variable_one=, :variable_two, :variable_two= ...]</pre><p>We see that new_instance has the four methods :variable_one, and :variable_one= , :variable_two and :variable_two=. These are the getter and setter methods that attr_accessor creates for us.</p><p>We can also verify that attr_accessor creates two instance variables:</p><pre>class MyClass<br>  attr_accessor :variable_one, :variable_two</pre><pre>  def initialize(param_one, param_two)<br>    self.variable_one = param_one<br>    self.variable_two = param_two<br>  end<br>end</pre><pre>new_instance = MyClass.new(&quot;one&quot;, &quot;two&quot;)</pre><pre>new_instance.instance_variables<br># =&gt; [:<a href="http://twitter.com/variable_one">@variable_one</a>, :<a href="http://twitter.com/variable_two">@variable_two</a>]</pre><p>So, somehow attr_accessor creates two instance variables and the public methods that allow us to get and set those instance variables. How does it do this? Let’s implement our own version of attr_accessor to find out.</p><p>Our own attr_accessor needs to do the following dynamically:</p><ol><li>Define instance variables.</li><li>Define public getter and setter methods.</li></ol><p>We eventually need a class that ‘looks’ like this:</p><pre># pseudocode</pre><pre>MyNewClass<br>  def &lt;instance_variable_name&gt;<br>    self.&lt;instance_variable_name&gt;<br>  end</pre><pre>  def &lt;instance_variable_name&gt;=(arg)<br>    self.&lt;instance_variable_name&gt; = arg<br>  end<br>end</pre><p>So this means we have to dynamically create instance methods whose names are the values from the arguments passed into attr_accessor, for example:</p><pre>MyNewClass<br>  attr_accessor(:method_one, :method_two)<br>end</pre><p>will result in a class that ‘looks’ like this:</p><pre>MyNewClass</pre><pre>  def method_one<br>    @method_one<br>  end</pre><pre>  def method_one=(arg)<br>    @method_one = arg<br>  end</pre><pre>  def method_two<br>    @method_two<br>  end</pre><pre>  def method_two=(arg)<br>    @method_two = arg<br>  end</pre><pre>end</pre><p>How do we go from calling attr_accessor to generating all those methods?</p><h4>define_method</h4><p>To define methods dynamically in Ruby, we can use the define_method method. define_method takes in an argument and a block. The first argument will be the name given to the newly defined method, and the block will become the body of the method:</p><pre>class MyNewClass</pre><pre>  def self.define_blah(attr)<br>    define_method(attr) {p &quot;i am the method created inside blah&quot;}<br>  end</pre><pre>end</pre><pre>MyNewClass.define_blah(&quot;my_new_method&quot;)</pre><p>This will result in a class that ‘looks’ like this:</p><pre>class MyNewClass</pre><pre>  def my_new_method<br>    p &quot;i am the method created inside blah&quot;<br>  end</pre><pre>  def self.define_blah(attr)<br>    define_method(attr) {p &quot;i am method created inside blah&quot;}<br>  end</pre><pre>end</pre><p>This means that we can do the following:</p><pre>a = MyNewClass.new</pre><pre>MyNewClass.define_blah(&quot;my_new_method&quot;)</pre><pre>a.my_new_method<br># =&gt; &quot;i am the method created inside blah&quot;</pre><p>Please note that the method self.blah, in which we use define_method, is a <em>class method. </em>This means when we run</p><pre>MyNewClass.define_blah(attr)</pre><p>we are also running in the body</p><pre>self.define_method(attr) {p “i am method created inside blah”}</pre><p>where self is MyNewClass.</p><p>To demonstrate this, let’s try</p><pre>class MyNewClass</pre><pre>  def self.define_blah(attr)<br>    define_method(attr) {p &quot;i am the method created inside blah&quot;}<br>  end</pre><pre>end</pre><pre>MyNewClass.define_blah(&quot;method_created&quot;)</pre><pre>a = MyNewClass.new</pre><pre>a.public_methods<br># =&gt; [:method_created, ...]</pre><p>This makes sense — we are changing the class MyNewClass by adding methods that will be available to instances of the class.</p><p><strong>Using </strong><strong>send to Define Methods Outside the Class</strong></p><p>If we try to call define_method directly on the class, we get a NoMethodError:</p><pre>class TestClass<br>end</pre><pre>TestClass.define_method(:blah) {p &quot;hello&quot;}<br># =&gt; private method `define_method&#39; called for TestClass:Class (NoMethodError)</pre><p>To successfully call define_method from outside the class, we can run MyNewClass.send(:define_method, “hello”) {p “hello”}:</p><pre>class MyNewClass<br>  def self.define_blah(attr)<br>    define_method(attr) {p “i am the method created inside blah”}<br>  end<br>end</pre><pre>MyNewClass.define_blah(“method_created”)<br>MyNewClass.send(:define_method, “hello”) {p “hello”}</pre><pre>a = MyNewClass.new</pre><pre>a.public_methods<br># =&gt; [:method_created, :hello, …]</pre><p>So now we have a new tool: define_method — and two ways to call it. Let’s use it to create the getter and setter methods for all instances of MyNewClass.</p><h4>Where to define my_attr_accessor?</h4><p>We need a way to define my_attr_accessor for all classes. Where do we define it? We call it at the class level, so we know it must be a class method, right? Sort of.</p><p>All user-defined Ruby classes are instances of the class Class:</p><pre>class MyNewClass<br>end</pre><pre>MyNewClass.class<br># =&gt; Class</pre><p>User-defined Ruby classes like MyNewClass have the same relationship to the class Class that objects have to their instantiating classes. That is — they are both instantiations of a class. So, in this way, we can think about MyNewClass as an object instantiated by the class Class.</p><p>Following this line of reasoning — where do we define methods we want to use on instances of the user-defined class? We define them in the instantiating class. What’s the instantiating class for a user-defined class? It’s the class Class. This means that we can define a method in Class and then access it in MyNewClass.</p><p>Put differently: all Ruby classes are instances of the Class class, so just like non-class objects have access to all instances methods defined in their instantiating classes, all instances of Class have access to the instance methods defined in their instantiating class, which is Class.</p><p>For example:</p><pre>class Class<br>  def my_attr_accessor(*attrs)<br>    &quot;hello&quot;<br>  end<br>end</pre><pre>new_class = Class.new</pre><pre>new_class.public_methods<br># =&gt; [:allocate, :new, :superclass, :my_attr_accessor,...]</pre><p>We see the methods that instances of Class have access to. This includes my_attr_accessor. Because all user-defined classes are instances of Class, all classes have access to my_attr_accessor.</p><pre>class Class<br>  def my_attr_accessor(*attrs)<br>    p &quot;hello from here&quot;<br>  end<br>end</pre><pre>class MyNewClass<br>  my_attr_accessor<br>end</pre><p>When this code is evaluated (meaning when I type ruby file_name.rb into the console), it outputs:</p><pre>&quot;hello from here&quot;</pre><p>So my_attr_accessor is a method that can be used in any instance of the Class class,<strong> but when is </strong><strong>my_attr_accessor actually run?</strong> In the code example above, there’s no point at which any methods are <em>called. </em>All we’ve done is define MyNewClass, but we haven’t explicitly called any methods. Does simply defining a class call its class-level methods? It turns out the answer is yes, sort of. From <a href="http://stackoverflow.com/a/4371087/4172664">StackOverflow</a>:</p><blockquote><em>The trick is that </em><em>class is not a definition in Ruby (it is &quot;just a definition&quot; in languages like C++ and Java), but it is an expression that evaluates. It is during this evaluation when the </em><em>attr_accessor method is invoked which in turn modifies the current class - remember the implicit receiver: </em><em>self.attr_accessor, where </em><em>self is the &quot;open&quot; class object at this point.</em></blockquote><p>This means that class in Ruby is an expression that evaluates — it’s not simply a definition. So, when Ruby sees:</p><pre>class MyNewClass<br>end</pre><p>it evaluates the methods called in the context of the class. In our case, my_attr_accessor is evaluated with the implicit self receiver, where self refers to the class itself. In our case, self refers to MyNewClass. MyNewClass is an <em>instance </em>of the Class class, which is where my_attr_accessor is defined.</p><p>It’s exactly the same as any object calling one of its instance methods: instances methods are not defined in the object itself; they are defined in the instantiating class.</p><p>So,</p><pre>class MyNewClass<br>  my_attr_accessor<br>end</pre><p>is the same as</p><pre>class MyNewClass<br>  self.my_attr_accessor<br>end</pre><p>where self refers to the class-object MyNewClass, which is an instantiation of the Class class. So, the method call self.my_attr_accessor will look in its instantiating class for the definition of the method.</p><p>If Ruby does not find my_attr_accessor in the Class class, it will look up Class’s ancestor chain for the method.</p><p>Just like user-defined classes, Class has an ancestor chain:</p><pre>Class.ancestors</pre><pre># =&gt; [Class, Module, Object, Kernel, BasicObject]</pre><p>If Ruby does not find my_attr_accessor in Class, it will go up the ancestor chain, starting with the Module class, until it finds the method definition:</p><pre>class Module<br>  def hello<br>    p &quot;hello from module&quot;<br>  end<br>end</pre><pre>class Class<br>end</pre><pre>class MyClass<br>  hello<br>end</pre><p>This outputs:</p><pre>&quot;hello from module&quot;</pre><p>So we see that user-defined classes like MyClass and objects instantiated from classes really aren’t that different. Both are instantiated by classes and have instance methods that are defined in their instantiating classes, which are part of a hierarchical method lookup chain.</p><p>Now that we understand in some detail how and when my_attr_accessor is called, let’s create it.</p><p>We know that my_attr_accessor will take in an array as an argument, so we can give it a parameter *attrs to account for the potentially varying length of the array.</p><pre>class Class<br>  def my_attr_accessor(*attrs)<br>  end<br>end</pre><p>We know we’re going to iterate through all of the attrs provided in the method invocation, so we can use Array#each:</p><pre>class Class<br>  def my_attr_accessor(*attrs)<br>    attrs.each do |attr|<br>      #iterate through each attr and implement getters and setters<br>    end<br>  end<br>end</pre><p>Now we can use our trusty define_method trick to create methods on the class that’s calling my_attr_accessor. To do this, we’re going to use instance_variable_get and instance_variable_set. These two methods give us easy ways to get and set instance variables.</p><pre>class MyClass<br>  def initialize<br>  end<br>end</pre><pre>a = MyClass.new</pre><pre>a.instance_variables<br># =&gt; []</pre><pre>a.instance_variable_set(:@a, &quot;hello&quot;)</pre><pre>a.instance_variables<br># =&gt; [:@a]</pre><pre>a.instance_variable_get(:@a)</pre><pre># =&gt; &quot;hello&quot;</pre><p>We pass these methods into define_method as blocks. These blocks will become the bodies of the methods created through define_method.</p><pre>class Class<br>  def my_attr_accessor(*attrs)<br>    attrs.each do |attr|</pre><pre>      define_method(attr) { instance_variable_get(&quot;@#{attr}&quot;) }<br>      <br>      define_method(&quot;#{attr}=&quot;) { |val| instance_variable_set<br>      (&quot;@#{attr}&quot;, val) }</pre><pre>    end<br>  end<br>end</pre><p>This means that any instantiation of Class that calls my_attr_accessor(:attr_one, :attr_two)will dynamically create on itself getter and setter methods.</p><p>Let’s walk through this signal flow:</p><ol><li>We define a class.</li></ol><pre>class MyNewClass<br>end</pre><p>2. We then call my_attr_accessor in the class. This method is run when Ruby evaluates class MyNewClass. Remember that my_attr_accessor is called with an implicit receiver, self, which refers to the class itself.</p><pre>class MyNewClass<br>  my_attr_accessor(:attribute_one, :attribute_two)<br>end</pre><p>3. Ruby looks in MyNewClass’s instantiating class (Class) for the definition of my_attr_accessor. In Class, we defined my_attr_accessor as follows:</p><pre>class Class<br>  def my_attr_accessor(*attrs)<br>    attrs.each do |attr|</pre><pre>      define_method(attr) { instance_variable_get(&quot;@#{attr}&quot;) }<br>      <br>      define_method(&quot;#{attr}=&quot;) { |val| instance_variable_set<br>      (&quot;@#{attr}&quot;, val) }</pre><pre>    end<br>  end<br>end</pre><p>5. my_attr_accessor iterates through the array of *attrs passed to it, and calls define_method on each attr, creating an instance variable getter and setter for each attribute.</p><p>6. Now our MyNewClass ‘looks’ like this:</p><pre>class MyNewClass</pre><pre>  def attribute_one<br>    instance_variable_get(<a href="http://twitter.com/attribute_one">@attribute_one</a>)<br>  end</pre><pre>  def attribute_one=(val)<br>    instance_variable_set(<a href="http://twitter.com/attribute_one">@attribute_one</a>, val)<br>  end</pre><pre>  def attribute_two<br>    instance_variable_get(<a href="http://twitter.com/attribute_two">@attribute_two</a>)<br>  end</pre><pre>  def attribute_two=(val)<br>    instance_variable_set(<a href="http://twitter.com/attribute_two">@attribute_two</a>, val)<br>  end</pre><pre>end</pre><p>7. Any instance of MyNewClass now has access to these methods:</p><pre>a = MyNewClass.new</pre><pre>a.public_methods<br># =&gt; [:attribute_one, :attribute_one=, :attribute_two, :attribute_two=, ...]</pre><pre>a.attribute_one = &quot;hello&quot;<br>a.attribute_two = &quot;world&quot;</pre><pre>a.instance_variables<br># =&gt; [:@attribute_one, :@attribute_two]</pre><pre>a.attribute_one<br># =&gt; hello</pre><pre>a.attribute_two<br># =&gt; world</pre><p>And so we have it — we’ve created our own version of attr_accessor, and in doing so, we’ve dug into several features of the Ruby language:</p><ol><li>Ruby’s object model (every user-defined class is an instantiation of Ruby’s Class class). In this way, we can think of every class as an object of class Class.</li><li>class is not simply a definition; it is an expression that’s evaluated. It is during this evaluation that methods called inside the class are invoked.</li><li>define_method dynamically creates methods in the context in which it’s called. It takes one argument, which becomes the method name, and a block, which becomes the method body.</li><li>instance_variable_get and instance_variable_set are two methods that allow us to get and set instance variables on an instance of a class.</li></ol><p>I hope this was a useful dive into attr_accessor and some of its supporting Ruby features!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d34e2ccc5477" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Proc.new Trick]]></title>
            <link>https://medium.com/@amliving/proc-new-trick-c1df16185599?source=rss-dac127fbd53------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1df16185599</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[lambda-function]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Andrew Livingston]]></dc:creator>
            <pubDate>Thu, 23 Feb 2017 19:54:53 GMT</pubDate>
            <atom:updated>2017-02-23T19:55:39.921Z</atom:updated>
            <content:encoded><![CDATA[<h4>Ruby’s Proc.new without an explicit block</h4><p>All Ruby developers know code like this, where a method takes a block, and the unary operator &amp; converts the block into a Proc that can be called with #call:</p><pre>def random_method(&amp;block)<br>  block.call<br>end</pre><pre>random_method {&quot;Hello&quot;}</pre><pre># =&gt; Hello</pre><p>Similarly, all Ruby developers know code like this, in which a method can yield to any block that is passed to it:</p><pre>def random_method_two<br>  yield<br>end</pre><pre>random_method_two {&quot;Hello&quot;}</pre><pre># =&gt; Hello</pre><p>However, there’s another way to pass and call blocks in methods:</p><pre>def random_method_three<br>  prok = Proc.new<br>  prok.call<br>end</pre><pre>random_method_three {&quot;Hello From Three&quot;}</pre><p>This method <em>looks</em> like it would raise an error because Proc.new must take a block, and when it doesn’t, Ruby raises this error:</p><pre>Proc.new<br># =&gt; ArgumentError: tried to create Proc object without a block</pre><p>But if we run the following code, even though we haven’t explicitly passed a block to Proc.new, Ruby raises no error:</p><pre>def random_method_three<br>  prok = Proc.new<br>  prok.call<br>end</pre><pre>random_method_three {&quot;Hello From Three&quot;}</pre><pre># =&gt; Hello From Three</pre><p>What’s happening here? Proc.new will look for a block in its context, find the block we passed into random_method_three, and run Proc.new with that block.</p><p>This is useful when you would like to create and use a Proc object inside of a method but would like ‘choose’ when to use the Proc. This avoids the performance overhead of using the &amp;block construction, which automatically converts any block passed to a method into a Proc object regardless of whether you want the Proc to be called in the method.</p><p>For example, take these two methods:</p><pre>def uses_ampersand(trigger, &amp;block)<br>  if trigger &amp;&amp; block_given?<br>    block.call<br>  end<br>end</pre><pre>def doesnt_use_ampersand(trigger)<br>  if trigger &amp;&amp; block_given?<br>    a = Proc.new<br>    a.call<br>  end<br>end</pre><p>The method uses_ampersand(trigger, &amp;block) will convert any block passed to it into a Proc object regardless of whether trigger is truthy or falsy, while doesnt_use_ampersand(trigger) will only create a Proc object if trigger is truthy. This difference in behavior results in a non-negligible performance difference. We can see this by using Ruby’s benchmark library.</p><p>The set up:</p><pre>require &#39;benchmark&#39;</pre><pre>def uses_ampersand(trigger, &amp;block)<br>  if trigger &amp;&amp; block_given?<br>    block.call<br>  end<br>end</pre><pre>def doesnt_use_ampersand(trigger)<br>  if trigger &amp;&amp; block_given?<br>    a = Proc.new<br>    a.call<br>  end<br>end</pre><pre>n = 4000000</pre><pre>Benchmark.bmbm do |test_case|<br>  test_case.report(&quot;Uses &amp;block&quot;) do<br>    n.times do<br>      uses_ampersand(false) do<br>        &quot;hello from block (won&#39;t get called)&quot;<br>      end<br>    end<br>  end<br>  test_case.report(&quot;Uses Proc.new&quot;) do<br>    n.times do<br>      doesnt_use_ampersand(false) do<br>        &quot;hello from block (won&#39;t get called)&quot;<br>      end<br>    end<br>  end<br>end</pre><p>When run, we see the performance difference:</p><pre>$ ruby proc_comparison.rb</pre><pre>Rehearsal -------------------------------------------------<br>Uses &amp;block     4.680000   0.200000   4.880000 (  5.014182)<br>Uses Proc.new   0.570000   0.000000   0.570000 (  0.583753)<br>---------------------------------------- total: 5.450000sec</pre><pre>                    user     system      total        real<br>Uses &amp;block     4.500000   0.160000   4.660000 (  4.721222)<br>Uses Proc.new   0.590000   0.010000   0.600000 (  0.669252)</pre><p>So, we see the method that explicitly takes a block and uses the &amp; operator to convert that block — every time — into a Proc is ~10x slower than the method that selectively uses the block only when trigger is truthy. This can be explained by the fact that uses_ampersand(trigger, &amp;block) will always create a Proc from the block that is passed into it, while doesnt_use_ampersand(trigger) will only sometimes — when we want it to, by passing in a truthy trigger — create a Proc.</p><p>I hope you found this helpful.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1df16185599" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ruby’s Unary ‘&’ Operator]]></title>
            <link>https://medium.com/@amliving/rubys-unary-operator-a93d36d3cd8b?source=rss-dac127fbd53------2</link>
            <guid isPermaLink="false">https://medium.com/p/a93d36d3cd8b</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Andrew Livingston]]></dc:creator>
            <pubDate>Mon, 20 Feb 2017 20:10:25 GMT</pubDate>
            <atom:updated>2017-02-20T20:10:25.050Z</atom:updated>
            <content:encoded><![CDATA[<h4>&amp;block party</h4><p>My goal in this post is to dig into and clarify some aspects of Ruby’s unary &amp; operator. This article assumes familiarity with blocks and Proc objects.</p><p>If you’ve used Ruby for just a little bit, you’ve likely seen code that looks like this:</p><pre>class TellMeAboutBlock<br>  def accept_block(&amp;block)<br>  end<br>end</pre><p>or this:</p><pre>[1,2].map(&amp;:to_s)<br># =&gt; [&quot;1&quot;, &quot;2&quot;]</pre><p>These two pieces of code have in common the use of &amp;, but what’s really happening here? In the first example, &amp; converts the block into a Proc object, and in the second example &amp; converts :to_s into a block that map can accept.</p><p>Generally, the unary &amp; operator converts blocks and non-Proc objects to Proc objects, and Proc objects into blocks. This <a href="http://ablogaboutcode.com/2012/01/04/the-ampersand-operator-in-ruby">Blog Post</a> nicely summarizes the three ways in which &amp;object is evaluated:</p><ol><li>If object is a block, &amp; converts object into a Proc.</li><li>If object is a Proc, &amp; &#39;unpacks’ the Proc object and treats it as a literal block.</li><li>If object is neither a block nor a Proc, &amp; first calls object.to_proc in an attempt to convert object into a Proc, and then converts the resulting Proc into a block.</li></ol><h4>&amp;block -&gt; Proc</h4><p>Let’s look at the first case, in which object is a block, and &amp; converts the object into a Proc.</p><pre>class TellMeAboutBlock<br>  def tell_me_class(&amp;block)<br>    p block.class<br>  end<br>end</pre><pre>n = TellMeAboutBlock.new</pre><pre>n.tell_me_class {p &quot;Random Block&quot;}<br># =&gt; Proc</pre><p>In this code, the method #tell_me_class(&amp;block) returns the class of the &amp;block argument. When n.tell_me_class {&quot;Random Block&quot;} is run, &quot;Proc&quot; is returned.</p><p>What’s interesting about this result is that block expressions like {|n| n+1} or {&quot;Random Block&quot;} are not Ruby objects; they do not have a class. For example, this will result in a SyntaxError:</p><pre>{|n| n+1}.class</pre><pre># =&gt; <br>SyntaxError: (irb):4: syntax error, unexpected &#39;|&#39;, expecting &#39;}&#39;</pre><p>This means that the method #tell_me_class does something to the &amp;block parameter it accepts to convert it into a Proc object. This is where the &amp; operator comes into the picture. When a method is defined, it can anticipate converting any block passed to it into a Proc object by prefixing the <em>last</em> parameter with the &amp; operator. The &amp;block parameter <em>must</em> be the <em>last</em> parameter in the method definition.</p><p>When the method is invoked and is given a block, the block will be converted into a Proc object. So, with our #tell_me_class method:</p><pre>class TellMeAboutBlock<br>  def tell_me_class(&amp;block)<br>    puts block.class<br>  end<br>end</pre><p>when we call tell_me_class and pass it a block:</p><pre>n = TellMeAboutBlock.new</pre><pre>n.tell_me_class {p &quot;Random Block&quot;}<br># =&gt; Proc</pre><p>the block passed to the method is converted into a Proc<em>. </em>It’s interesting to note that yield still works, even if the block is converted into a Proc object. For example:</p><pre>class TellMeAboutBlock<br>  def tell_me_class(&amp;block)<br>    puts block.class<br>    yield<br>  end<br>end</pre><pre>n = TellMeAboutBlock.new</pre><pre>n.tell_me_class {p &quot;Random Block&quot;}</pre><pre># =&gt;<br>Proc<br>&quot;Random Block&quot;</pre><p>Now what happens if we pass a Proc object directly into the #tell_me_class method? Like this:</p><pre>class TellMeAboutBlock<br>  def tell_me_class(&amp;block)<br>    puts block.class<br>  end<br>end</pre><pre>n = TellMeAboutBlock.new<br>my_proc = Proc.new {p &quot;Random Block&quot;}</pre><pre>n.tell_me_class(my_proc)<br># =&gt; wrong number of arguments (1 for 0) (ArgumentError)</pre><p>This results in an ArgumentError because #tell_me_class expects a block, not a ‘normal’ argument.</p><p>But remember the second way &amp;object is evaluated:</p><blockquote>If object is a Proc, &amp; unpacks object and passes it as a block.</blockquote><h4>&amp;Proc -&gt; block</h4><p>Let’s give it a shot. If we use &amp; to unpack my_proc and allow Ruby to pass it as a literal block:</p><pre>n.tell_me_class(&amp;my_proc)<br># =&gt; Proc</pre><p>it evaluates correctly again. Also of note is that &amp;block preserves the lambda status of a Proc:</p><pre>my_lam = -&gt;(n) { n.to_s}</pre><pre>n.tell_me_class(&amp;my_lam)</pre><pre># =&gt; #&lt;Proc:0x007fe07502e3f8@proc_post.rb:15 (lambda)&gt;</pre><p>One question that arises is: why do we get an ArgumentError — as opposed to a TypeError — when we pass a non-Proc object into #tell_me_class?Doesn’t this method take one argument, a block?</p><p>It turns out that even though the method takes a &amp;block parameter, the arity<em> </em>(the number of arguments a method takes) does not include the &amp;block parameter. The<em> </em>arity of the tell_me_class(&amp;block) method is 0, shown here:</p><pre>class TellMeAboutBlock<br>  def tell_me_class(&amp;block)<br>    puts block.class<br>  end<br>end</pre><pre>n = TellMeAboutBlock.new</pre><pre>n.method(:tell_me_class).arity<br># =&gt; 0 </pre><p>Similarly, a method with two parameters — one of which is &amp;block — will have an arity of 1:</p><pre>class TellMeAboutBlock<br>  def two_params_one_is_block(param, &amp;block)<br>  end<br>end</pre><pre>n = TellMeAboutBlock.new</pre><pre>n.method(:two_params_one_is_block).arity<br># =&gt; 1</pre><p>Passing a Ruby object (e.g. Proc objects, FixNum objects, String objects, etc.) as an argument into a method that takes only a &amp;block parameter will result in an ArgumentError because the method does not expect any non-block arguments.</p><p>For example:</p><pre>class TellMeAboutBlock<br>  def tell_me_class(&amp;block)<br>    puts block.class<br>  end<br>end</pre><pre>n = TellMeAboutBlock.new</pre><pre>my_proc = Proc.new {p &quot;Random Block&quot;}</pre><pre>n.tell_me_class(my_proc)<br># =&gt; wrong number of arguments (1 for 0) (ArgumentError)</pre><pre>n.tell_me_class(1)<br># =&gt; wrong number of arguments (1 for 0) (ArgumentError)</pre><pre>n.tell_me_class(&quot;Hello&quot;)<br># =&gt; wrong number of arguments (1 for 0) (ArgumentError)</pre><p>you can, however, pass nothing into this method and not receive an error:</p><pre>n.tell_me_class()<br># =&gt; NilClass</pre><p>From the perspective of the method, no block has been provided, so &amp;block is nil.</p><p>However, passing nil explicitly results in an ArgumentError.</p><pre>n.tell_me_class(nil)<br># =&gt; wrong number of arguments (1 for 0) (ArgumentError)</pre><p>This is because nil in Ruby is not ‘nothing’ — it is an object of the NilClass, so the method tell_me_class perceives it is receiving one argument, which violates its arity (0).</p><h4><strong>Small Note On Performance</strong></h4><p>Converting a block into a Proc is not cheap, and it is advisable when possible to use yield instead of block.call inside the method.</p><p>This is preferable:</p><pre>class TellMeAboutBlock<br>  def tell_me_class(&amp;block)<br>    yield<br>  end<br>end</pre><p>To this:</p><pre>class TellMeAboutBlock<br>  def tell_me_class(&amp;block)<br>    block.call<br>  end<br>end</pre><p>Feel free to read more about the performance of block.call vs yield in <a href="http://mudge.name/2011/01/26/passing-blocks-in-ruby-without-block.html">this blog post</a>, which benchmarks the two strategies.</p><h4>&amp;non-Proc -&gt; block</h4><p>Now we come to the third way in which &amp;object is evaluated:</p><blockquote>If object is neither a block nor a Proc, &amp; first calls object.to_proc in an attempt to convert object into a Proc, and then converts the resulting Proc into a block.</blockquote><p>A common example of this is:</p><pre>[1,2].map(&amp;:to_s)<br># =&gt; [&quot;1&quot;, &quot;2&quot;]</pre><p>What’s happening here? First, we know that map can take a block. From the <a href="http://ruby-doc.org/core-2.4.0/Enumerable.html#method-i-map">Ruby Docs</a>:</p><blockquote>map { |obj| block } → array</blockquote><blockquote>Returns a new array with the results of running <em>block</em> once for every element in <em>enum</em>.</blockquote><p>map can only take a block or nothing at all; it cannot take a Proc object. If we try to pass a Proc into map, we see the familiar ArgumentError:</p><pre>my_proc = Proc.new {|n| n.to_s}<br>[1,2].map(my_proc)<br># =&gt; wrong number of arguments (1 for 0) (ArgumentError)</pre><p>But, as before, we can use &amp; to convert the Proc into a block and pass it into map:</p><pre>my_proc = Proc.new {|n| n.to_s}<br>[1,2].map(&amp;my_proc)<br># =&gt; [&quot;1&quot;, &quot;2&quot;]</pre><p>So, &amp;:to_s in [1,2].map(&amp;:to_s) must be generating a block somehow. At first glance, we see the &amp; operator, so we think: “This must either be converting a block into a Proc or a Proc into a block.” Since map only takes a block, the latter must the case. However, Ruby does not see a Proc object; instead, it sees :to_s. How then does :to_s become a Proc for Ruby to convert into a block?</p><p>The answer is that Ruby calls #to_proc on the object after the &amp; (:to_s in this case).</p><p>To verify this is true, let’s take a slight detour and write our own#to_proc method in our own MyFineClass. Then when we call [1,2,3].map(&amp;MyFineClass.new), we should see &quot;hello&quot; on the console.</p><pre>class MyFineClass<br>  def to_proc<br>    puts &quot;hello&quot;<br>  end<br>end</pre><pre>my_fine_object = MyFineClass.new<br>[1,2,3].map(&amp;my_fine_object)<br># =&gt; hello</pre><p>Good, so we’ve verified that if &amp; is followed by a non-Proc object, Ruby will attempt to convert the non-Proc object into a Proc by calling #to_proc on the non-Proc object.</p><p>Now, the reason we often see expressions like [1,2].map(&amp;:to_s) is that :to_s is a Symbol , and Symbol has a #to_proc method that returns a Proc object:</p><pre>:to_s.to_proc<br># =&gt; #&lt;Proc:0x007fd0051133e8&gt;</pre><p>A String object, however, does not have a #to_proc method:</p><pre>&quot;to_s&quot;.to_proc<br># =&gt; NoMethodError: undefined method `to_proc&#39; for &quot;to_s&quot;:String</pre><p>And this is why we don’t see:</p><pre>[1,2].map(&amp;&quot;to_s&quot;)</pre><p>So when [1,2].map(&amp;:to_s) is executed, Ruby calls to_proc on :to_s and converts :to_s into a Proc.</p><p>We can quickly recreate for illustrative purposes a naive version of Symbol#to_proc:</p><pre>class Symbol<br>  def to_proc<br>    -&gt;(object){object.send(self)}<br>  end<br>end</pre><p>The idea behind Symbol#to_proc is that it returns a Proc that takes the Symbol (:to_s in this case) and calls it as a method on the Proc argument (object), using Ruby’s send method. self in this particular case is :to_s.</p><p>The Proc returned by Symbol#to_proc is then converted into a block by &amp; and is passed into map:</p><pre>[1,2].map(&amp;-&gt;(object){object.send(:to_s)})</pre><p>map will successively iterate over [1,2] and first evaluate 1.send(:to_s), then2.send(:to_s).</p><p>Let’s recap these steps. The signal flow for [1,2].map(&amp;:to_s) is:</p><ol><li>Ruby sees &amp; and expects a Proc after the &amp;.</li><li>Instead, Ruby sees a Symbol, :to_s, so it calls :to_s.to_proc to convert it into a Proc. This Proc will look like this:</li></ol><pre>-&gt;(object){object.send(:to_s)}</pre><p>3. Ruby must now convert the Proc into a block because it is passed to map, which takes a block. &amp; converts a Proc into a block, so now the expression looks like this:</p><pre>[1,2].map(&amp;-&gt;(object){object.send(:to_s)})</pre><p>4. For each element in the [1,2] array, the block is called, using each element of the array as the argument. For example, the first iteration of [1,2].map(&amp;:to_s) will include the following call:</p><pre>-&gt;(n){n.send(:to_s)}.call(1)</pre><p>And the second iteration will include this call:</p><pre>-&gt;(n){n.send(:to_s)}.call(2)</pre><p>5. When [1,2].map(&amp;:to_s) finishes iterating, it returns a new array: [&quot;1&quot;,&quot;2&quot;] , as we’d expect.</p><p>The unary &amp; operator is an essential part of Ruby, as it’s a multifaceted tool that wields blocks andProc objects.</p><p>I hope this was helpful. Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a93d36d3cd8b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ActiveRecord’s Select & Pluck]]></title>
            <link>https://medium.com/@amliving/activerecords-select-pluck-3d5c58872053?source=rss-dac127fbd53------2</link>
            <guid isPermaLink="false">https://medium.com/p/3d5c58872053</guid>
            <category><![CDATA[ruby-on-rails-development]]></category>
            <category><![CDATA[activerecord]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Andrew Livingston]]></dc:creator>
            <pubDate>Thu, 16 Feb 2017 03:29:28 GMT</pubDate>
            <atom:updated>2017-02-16T03:29:28.397Z</atom:updated>
            <content:encoded><![CDATA[<h4>Column Down</h4><p>select and pluck are two different and useful ways to return the values from one or more columns in a database table as a collection. For example, imagine you have a questions table in your database. Each question might have three fields: id, question_text, and a foreign_key from an associated table. To return the values from <em>only </em>the question_text column, you would use select or pluck. I’d like to explore the differences between these two methods and end with an application of pluck inside a Rails application.</p><h4>Select</h4><p>select works in <a href="http://apidock.com/rails/ActiveRecord/QueryMethods/select">two unique ways</a>:</p><p><em>i</em>.select takes a block and works just like Array#select.</p><pre>Model<strong>.</strong>all<strong>.</strong><a href="http://apidock.com/rails/ActiveRecord/QueryMethods/select">select</a> <strong>{</strong> <strong>|</strong>m<strong>|</strong> m<strong>.</strong>field <strong>==</strong> value <strong>}</strong></pre><p>This builds an array of Ruby objects from the database for the scope, converting them into an array and iterating through them using Array#select.</p><blockquote><strong>select <em>vs</em> </strong><strong>where</strong></blockquote><blockquote><em>Passing a block into </em><em>select with a large data set (i.e. many rows) is slower than using other strategies, like </em><em>where:</em></blockquote><blockquote><em>Model.where(field: value)</em></blockquote><blockquote><em>because with </em><em>Model</em><strong><em>.</em></strong><em>all</em><strong><em>.</em></strong><a href="http://apidock.com/rails/ActiveRecord/QueryMethods/select"><em>select</em></a><em> </em><strong><em>{</em></strong><em> </em><strong><em>|</em></strong><em>m</em><strong><em>|</em></strong><em> m</em><strong><em>.</em></strong><em>field </em><strong><em>==</em></strong><em> value </em><strong><em>}, </em></strong><em>Rails will first convert all of the table rows into Ruby objects, and then run the given block for each Ruby object, while </em><em>Model.where(field: value) generates a SQL statement that offloads the heavy lifting to SQL, which is faster than Ruby for this type of filtering.</em></blockquote><p><em>ii. </em>select modifies the SELECT statement for the SQL query so that only certain fields are retrieved:</p><pre>Model<strong>.</strong><a href="http://apidock.com/rails/ActiveRecord/QueryMethods/select">select</a><strong>(</strong>:field<strong>)</strong><br><em># =&gt; [#&lt;Model id: nil, field: &quot;value&quot;&gt;]</em></pre><p>For example, from a project of mine:</p><pre>Question.select(:question_text)<br># =&gt; #&lt;ActiveRecord::Relation [#&lt;Question id: nil, question_text: &quot;What&#39;s 2+2?&quot;&gt;, ...]&gt;</pre><p>This generates the following SQL:</p><pre>SELECT &quot;questions&quot;.&quot;question_text&quot; FROM &quot;questions&quot;</pre><p>Please note that in this second example, the select method does <em>not</em> return an array; it returns an ActiveRecord::Relation object. As a result, you can chain other <a href="http://apidock.com/rails/ActiveRecord/QueryMethods">ActiveRecord::QueryMethods</a> to it. For example:</p><pre>Question<strong>.</strong><a href="http://apidock.com/rails/ActiveRecord/QueryMethods/select">select</a><strong>(</strong>:question_text).limit(5)</pre><pre># =&gt; #&lt;ActiveRecord::Relation [#&lt;Question id: nil, question_text: &quot;What&#39;s 2+2?&quot;&gt;, #&lt;Question id: nil, question_text: &quot;What&#39;s 2+3?&quot;&gt;, #&lt;Question id: nil, question_text: &quot;What&#39;s 3+3?&quot;&gt;, #&lt;Question id: nil, question_text: &quot;What&#39;s 2+9?&quot;&gt;, #&lt;Question id: nil, question_text: &quot;What&#39;s 10+2?&quot;&gt;]&gt;</pre><p>This generates the following SQL:</p><pre>SELECT  &quot;questions&quot;.&quot;question_text&quot; FROM &quot;questions&quot; LIMIT ?  [[&quot;LIMIT&quot;, 5]]</pre><h4>Pluck</h4><p>From the <a href="http://guides.rubyonrails.org/active_record_querying.html#pluck">Rails Guides</a>:</p><blockquote>pluck can be used to query single or multiple columns from the underlying table of a model. It accepts a list of column names as argument and returns an array of values of the specified columns with the corresponding data type.</blockquote><p>The important point here is that pluck <strong>returns an array.</strong> It does not return an ActiveRecord::Relation object, like select. So, for example:</p><pre>Question.pluck(:question_text)</pre><pre># =&gt; [&quot;Text1&quot;, &quot;Text2&quot;, ...]</pre><pre># this returns <strong>an array</strong> with all of the values from the question_text column from the questions table.</pre><p>Because pluck converts a database query result into a Ruby array without constructing an ActiveRecord object it’s more performant than select.</p><p>However, that pluck returns an array means you cannot chain standard ActiveRecord queries onto pluck. Doing so will return a NoMethodError:</p><pre>Question.pluck(:question_text).limit(5)</pre><pre># =&gt; NoMethodError: undefined method `limit&#39; for #&lt;Array:0x007fc5c1dfb3b0&gt;</pre><p>But pluck does work on ActiveRecord objects, so the following will return the expected result:</p><pre>Question.limit(5).pluck(:question_text)</pre><pre>#=&gt; [&quot;Text1&quot;, &quot;Text2&quot;, &quot;Text3&quot;, &quot;Text4&quot;, &quot;Text5&quot;]</pre><p>pluck can take multiple arguments to construct a multidimensional array:</p><pre>Question.pluck(:question_text, :course_id)</pre><pre>#=&gt; [[&quot;Text1&quot;, 16], [&quot;Text2&quot;, 23], ...]</pre><h4>When Would I Use Pluck ?</h4><p>I’ve used pluck to scope ActiveRecord model objects to determine which model objects have associated records in another table.</p><p>For example, take the following class:</p><pre>class Appointment &lt; ActiveRecord::Base<br>  <br>  has_many :charges</pre><pre>end</pre><p>If we want to determine which appointments have charges and which ones do not, we can use pluck in a scope. Here’s how:</p><p>First, remember that for Model.where(field: value), value can either be a single object (like integer, string, etc.), or it can be an array of objects.</p><p>So, the following is valid and will return all appointments with ids that are included in the array.</p><pre>Appointment.where(id: [1,2,3,4,5])</pre><pre># =&gt; returns all appointments with ids that are included in the array</pre><p>Well, we know that pluck returns an array, so we can construct an array that includes the foreign keys we want to scope in the associated model. For example, if we want to determine which appointments have associated charges, we can create an array from the appointment_id column of the charges table, like this:</p><pre>Charge.pluck(:appointment_id)</pre><pre># =&gt; returns an array with all of the appointment_ids from the charges table, like: [1,2,3,4,5]</pre><p>To determine which appointments have associated charges, we can write:</p><pre>Appointment.where(id: Charge.pluck(:appointment_id))</pre><pre># this is the same as Appointment.where(id: [1,2,3,4,5])</pre><p>And converting this into a scope on the Appointment model:</p><pre>class Appointment &lt; ActiveRecord::Base<br>  has_many :charges</pre><pre>  scope :received_payment_info, -&gt; {    <br>        where(id: Charge.pluck(:appointment_id)) }</pre><pre>end</pre><p>So now when we want to determine which appointments have associated charges, we can write:</p><pre>Appointment.received_payment_info</pre><pre>#=&gt; #&lt;ActiveRecord::Relation [#&lt;Appointment id: 1 &gt;, ...]</pre><p>which generates the following SQL queries:</p><pre>SELECT &quot;charges&quot;.&quot;appointment_id&quot; FROM &quot;charges&quot;</pre><pre>SELECT &quot;appointments&quot;.* FROM &quot;appointments&quot; WHERE (&quot;appointments&quot;.&quot;id&quot; IN (35, 44, 82) OR &quot;appointments&quot;.&quot;id&quot; IS NULL)</pre><p>pluck allowed us to:</p><ol><li>efficiently query an associated database table to…</li><li>generate an array from the associated table with all of the foreign_keys of objects from the primary table</li><li>use that array to determine which objects in the primary table have associated objects in the secondary table</li></ol><p>I hope you found this helpful. Enjoy plucking and selecting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3d5c58872053" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Recreating Ruby’s Enumerable]]></title>
            <link>https://medium.com/@amliving/recreating-rubys-enumerable-7a8b898b8482?source=rss-dac127fbd53------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a8b898b8482</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[enumerable]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Andrew Livingston]]></dc:creator>
            <pubDate>Wed, 15 Feb 2017 01:00:47 GMT</pubDate>
            <atom:updated>2017-02-15T01:00:47.023Z</atom:updated>
            <content:encoded><![CDATA[<h4>include LearnByDoing</h4><p>In this post, I’d like to dig into Ruby’s Enumerable module by building our own version, called MyEnumerable, with the map and select methods.</p><h4>Enumerable basics</h4><p>Ruby’s Enumerable module is indispensable for any Ruby programmer. It provides methods like each, select, and inject to collection objects.</p><p>From the <a href="http://ruby-doc.org/core-2.4.0/Enumerable.html">Ruby Docs</a>:</p><blockquote>The Enumerable mixin provides collection classes with several traversal and searching methods, and with the ability to sort. The class must provide a method each, which yields successive members of the collection.</blockquote><p>If you’ve used code that looks like this:</p><pre>[1,2,3,4].select{|n| n.odd?}</pre><p>or this:</p><pre>[1,2,3,4].map{|n| n+1}</pre><p>then you’ve used Enumerable. It’s important to realize that select and map are not instance methods of the Array class itself; they are methods that come with the Enumerable module, which is included by default in the Array class.</p><p>To use Enumerable in your own class, include it with a simple include Enumerable addition to the class definition, like so:</p><pre>class MyClass<br>  include Enumerable</pre><pre>  #...rest of code....must include an #each method<br>end</pre><p>You must provide an #each method that can successively iterate through the elements of the MyClass collection object. Please read <a href="https://medium.com/@amliving/how-i-think-about-rubys-enumerable-38219350696#.gr0ow0xak">my other post on the ‘</a><a href="https://medium.com/@amliving/how-i-think-about-rubys-enumerable-38219350696#.gr0ow0xak">#each contract’</a> to learn more about why this is necessary.</p><h3>Enumerable, how do you do it?</h3><p>To better understand what’s happening under the hood, let’s build our own version of Enumerable with map and select. We’ll call it MyEnumerable.</p><p>We know that both map and select take blocks as arguments, so we can begin with a skeleton our MyEnumerable module:</p><pre>module MyEnumerable</pre><pre>  def map(&amp;block)<br>  end</pre><pre>  def select(&amp;block)<br>  end</pre><pre>end</pre><h4>Implementing Map</h4><p>The Ruby Docs define map as follows:</p><blockquote>Returns a new array with the results of running <em>block</em> once for every element in <em>enum</em>.</blockquote><p>So, when map is invoked on the collection object, it iterates through the collection and runs the block once for each element of the collection. The resulting values are returned in the same order in a new array. For example:</p><pre>[1,2,3,4].map{|n| n+1}<br>#=&gt; [2,3,4,5]</pre><p>To implement our own version of map, let’s first create an empty array, which we’ll use to store the values returned from calling the block on each element of the collection object.</p><pre>module MyEnumerable</pre><pre>  def map(&amp;block)<br>    result = []<br>  end</pre><pre>end</pre><p>To iterate successively through every member of the collection object, we can use the each method defined in the collection object’s class.</p><p>Array has an each method, for example, defined as:</p><blockquote>Calls the given block once for each element in self, passing that element as a parameter.</blockquote><p>Let’s add the each method to our map method:</p><pre>module MyEnumerable</pre><pre>  def map(&amp;block)<br>    result = []<br>    self.each do |element|<br>    end<br>  end</pre><pre>end</pre><p>self here refers to the calling collection object. So, in our example earlier</p><pre>[1,2,3,4].map{|n| n+1}</pre><p>the collection object is the array [1,2,3,4] . This means that in MyEnumerable, self would be this [1,2,3,4] array.</p><p>Now that we can iterate over each element, let’s call the provided &amp;block for each element, using that element as the argument to the block, and successively insert each returned value into the result array.</p><pre>module MyEnumerable</pre><pre>  def map(&amp;block)<br>    result = []<br>    self.each do |element|<br>      result &lt;&lt; block.call(element)<br>    end<br>  end</pre><pre>end</pre><p>Now the result array will be [2,3,4,5]. The last step is to return the result array:</p><pre>module MyEnumerable</pre><pre>  def map(&amp;block)<br>    result = []<br>    self.each do |element|<br>      result &lt;&lt; block.call(element)<br>    end<br>    result<br>  end</pre><pre>end</pre><p>We’ve implemented a map method for our own MyEnumerable module. Let’s see how it works by using it with a FakeArrayWrapper class that will allow us to test array-like objects without falling back to the actual Array class. We have to use a <em>fake</em> array class for testing our MyEnumerable module; otherwise, if we called map on a real Array object, the map from the real Enumerable , and not from our fake MyEnumerable, would be called.</p><p>Here is our FakeArrayWrapper class. It contains the necessary each iteration method.</p><pre>class FakeArrayWrapper<br>  include MyEnumerable</pre><pre>  def initialize(*args)<br>    @fake_array = args.flatten<br>  end</pre><pre>  def each(&amp;block)<br>    @fake_array.each(&amp;block)<br>    self #return the original array<br>  end<br>end</pre><p>Calling map on an instance of the FakeArrayWrapper should work. Let’s give it a shot:</p><pre>fake_array_instance = FakeArrayWrapper.new([1,2,3,4])</pre><pre>fake_array_instance.map {|n| n + 1}<br>#=&gt; [2,3,4,5]</pre><pre>fake_array_instance.map {|n| n + 5}<br>#=&gt; [6,7,8,9]</pre><pre>fake_array_instance.map {|n| 1}<br>#=&gt; [1,1,1,1]</pre><p>And it works as expected. To summarize, we</p><ol><li>Created a MyEnumerable module with a map method.</li><li>The map method iterates over the calling object with the each method from the calling collection object’s class.</li><li>For each element in the collection object, map calls the &amp;block provided by the obj.map(&amp;block) invocation, using the element as the argument to the block, and inserts the resulting value into a result array.</li><li>When self.each has iterated over all of the collection object’s elements, map returns the result array.</li></ol><h4>Implementing Select</h4><p>The Ruby Docs define select as follows:</p><blockquote>Returns an array containing all elements of enum for which the given block returns a true value.</blockquote><p>So, for example,</p><pre>[1,2,3,4].select{|n| n==1}<br>#=&gt; [1]</pre><pre>[1,2,3,4].select{|n| n.odd?}<br>#=&gt; [1,3]</pre><pre>[1,2,3,4].select{|n| n.even?}<br>#=&gt; [2,4]</pre><p>Implementing map in the last section gave us the general approach for writing our own methods in MyEnumerable:</p><ol><li>Iterate over the elements of the calling collection object using each, and call the provided block iteratively with the iterated element as the argument.</li><li>Insert the resulting values into a result array inside the method.</li><li>Return the result array.</li></ol><p>So, for select, we will only include the elements of the collection object for which the called block returns true :</p><pre>module MyEnumerable</pre><pre>  def select(&amp;block)<br>    result =[]<br>    self.each do |element|<br>      result &lt;&lt; element if block.call(element) == true<br>    end<br>    result<br>  end</pre><pre>end</pre><p>Let’s give it a shot, again using the FakeArrayWrapper class:</p><pre>class FakeArrayWrapper<br>  include MyEnumerable</pre><pre>  def initialize(*args)<br>    @fake_array = args.flatten<br>  end</pre><pre>  def each(&amp;block)<br>    @fake_array.each(&amp;block)<br>    self #return the original array<br>  end<br>end</pre><p>Now calling select on instances of FakeArrayWrapper should work as expected:</p><pre>fake_array_instance = FakeArrayWrapper.new([1,2,3,4])</pre><pre>fake_array_instance.select {|n| n==1}<br># =&gt; [1]</pre><pre>fake_array_instance.select {|n| n.odd?}<br># =&gt; [1,3]</pre><pre>fake_array_instance.select {|n| n.even?} <br># =&gt; [2,4]</pre><p>Great!</p><p>Our simple MyEnumerable module now looks like</p><pre>module MyEnumerable</pre><pre>  def map(&amp;block)<br>    result = []<br>    self.each do |element|<br>      result &lt;&lt; block.call(element)<br>    end<br>    result<br>  end</pre><pre>  def select(&amp;block)<br>    result =[]<br>    self.each do |element|<br>      result &lt;&lt; element if block.call(element) == true<br>    end<br>    result<br>  end</pre><pre>end</pre><p>Both methods use each to iterate through the elements of the collection object that calls the method. The methods then insert the values returned from passing the iterated element as an argument into the provided block, into a result array. This result array is then the return value of calling map or select on a collection class object that includes MyEnumerable.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a8b898b8482" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Think About Ruby’s Enumerable]]></title>
            <link>https://medium.com/@amliving/how-i-think-about-rubys-enumerable-38219350696?source=rss-dac127fbd53------2</link>
            <guid isPermaLink="false">https://medium.com/p/38219350696</guid>
            <category><![CDATA[enumerable]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Andrew Livingston]]></dc:creator>
            <pubDate>Tue, 14 Feb 2017 22:52:30 GMT</pubDate>
            <atom:updated>2017-02-15T01:11:35.565Z</atom:updated>
            <content:encoded><![CDATA[<h4>Call the lawyers; it’s a contract.</h4><p>I’d like to give a high level demonstration of how Ruby’s Enumerable module requires an #each method from classes that include it.</p><p>I heard Armando Fox, an EECS professor at UC Berkeley, describe Enumerable as a ‘contract’ between the class that includes it and the module itself. That is, Enumerable makes the following deal with the classes that include it:</p><blockquote>“If you provide me with a way to iterate, or <em>enumerate, </em>over each instance of yourself, I will give you various useful methods in return.”</blockquote><p>The way classes provide this iteration to Enumerable is through an #each method. It’s a contract that exchanges #each for use of the methods in Enumerable. This includes map, select, and inject.</p><p>From <a href="http://ruby-doc.org/core-2.4.0/Enumerable.html">The Ruby Docs</a>:</p><blockquote>The class must provide a method #each, which yields successive members of the collection.</blockquote><p>It makes sense that for a class to use Enumerable, the class must provide an #each method; otherwise, Enumerable wouldn’t know how to successively access each element in a collection.</p><h4>Diving Into The Contract</h4><p>Let’s see what happens when a class does not provide an #each method and an instance of the class tries to call select and map. To do this, we’ll create a FakeArrayWrapper class that omits the #each method. We can think about FakeArrayWrapper as a wrapper on the Array class.</p><pre>class FakeArrayWrapper</pre><pre>  include Enumerable</pre><pre>  def initialize(*args)<br>    @fake_array = args.flatten<br>  end<br>    <br>  #we omit the #each method here</pre><pre>end</pre><p>When we try to call anEnumerable method, select, on an instance ofFakeArrayWrapper, the invocation returns an error.</p><pre>fake_array_instance = FakeArrayWrapper.new([1,2,3,4])</pre><pre>fake_array_instance.select {|n| n == 1} <br># =&gt;</pre><pre>fake_array.rb:17:in `select&#39;: undefined method `each&#39; for #&lt;FakeArrayWrapper:0x007fed5e816c00 <a href="http://twitter.com/fake_array">@fake_array</a>=[1, 2, 3, 4]&gt; (NoMethodError)<br> from fake_array.rb:17:in `&lt;main&gt;&#39;</pre><p>Similarly, we get an error when calling map :</p><pre>fake_array_instance = FakeArrayWrapper.new([1,2,3,4])</pre><pre>fake_array_instance.map {|n| n + 1}<br># =&gt;</pre><pre>fake_array.rb:20:in `map&#39;: undefined method `each&#39; for #&lt;FakeArrayWrapper:0x007f87908179e0 <a href="http://twitter.com/fake_array">@fake_array</a>=[1, 2, 3, 4]&gt; (NoMethodError)<br> from fake_array.rb:20:in `&lt;main&gt;&#39;</pre><p>These NoMethodError errors tell us that select and map from Enumerable tried to use a method called #each on the calling object (in this case fake_array_instance), but that this method doesn’t exist for instances of FakeArrayWrapper.</p><p>We knew this already; we didn’t define #each in the FakeArrayWrapper class.</p><p>Ruby was saying here:</p><blockquote>“I tried to call select and map on your fake_array_instance, but in order to do that, I needed you to give me an #each method for the <em>fake_array_instance</em>.”</blockquote><p>Note that the FakeArrayWrapper class does not change the behavior of the real Array class. Calling the same Enumerable methods on a real Array instance still returns the expected:</p><pre>real_array = [1,2,3,4]</pre><pre>real_array.select {|n| n == 1} <br># =&gt;[1]</pre><pre>real_array.map {|n| n + 1} <br># =&gt;[2,3,4,5]</pre><p>Now, if we implement the #each method in FakeArrayWrapper :</p><pre>class FakeArrayWrapper</pre><pre>  include Enumerable</pre><pre>  def initialize(*args)<br>    @fake_array = args.flatten<br>  end</pre><pre>  #now we implement #each<br>  def each(&amp;block)<br>    @fake_array.each(&amp;block) <br>    self #return the original array<br>  end</pre><pre>end</pre><p>the Enumerable methods return the expected values for the fake_array_instance :</p><pre>fake_array_instance = FakeArrayWrapper.new([1,2,3,4])</pre><pre>fake_array_instance.select {|n| n == 1} <br># =&gt;[1]</pre><pre>fake_array_instance.map {|n| n + 1} <br># =&gt;[2,3,4,5]</pre><p>We no longer receive the NoMethodError because now FakeArrayWrapper#each is implemented, and select and map can call fake_array_instance.each(&amp;block) without a problem.</p><p>So, in order for classes including Enumerable to use Enumerable’s methods, the including class must provide an #each method that allows Enumerable to iterate over the class instance’s elements.</p><p>In <a href="https://medium.com/@amliving/recreating-rubys-enumerable-7a8b898b8482#.g90rqg1tx">another post</a>, I implement my own version of Enumerable, called MyEnumerable, with map and select, to shed some light on the inner workings of Enumerable.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38219350696" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>