<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/css" href="/stylesheets/rss.css"?>
<rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/">
  <channel>
    <title>Flvorful Bloggage: Tag ruby</title>
    <link>http://blog.flvorful.com/articles/tag/ruby</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description></description>
    <item>
      <title>A Simple Pattern for Ruby's inject method</title>
      <description>&lt;p&gt;Ruby&amp;#8217;s &lt;code&gt;inject&lt;/code&gt; is an often misunderstood method, but you would be surprised at how much it can help you clean up your code. I see many developers skipping over this method in favor of the non-injectified way, mainly because they dont get how to use inject properly.  So we&amp;#8217;ll take a look at some common examples and then you will be able to see the pattern that allows you to take advantage of &lt;code&gt;inject&lt;/code&gt;.  Let&amp;#8217;s take a look at inject&amp;#8217;s signature:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;enum.inject(initial) {| memo, obj | block } =&amp;gt; obj
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This method is part of the &lt;code&gt;Enumerable&lt;/code&gt; module, so you can use this method on many different types, including Arrays, Hash, Strings and many others. Now, let&amp;#8217;s take a look at each part of the signature:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;&lt;code&gt;initial&lt;/code&gt; - this is the initial value that you want to set for the memo&lt;/li&gt;
&lt;li&gt;&lt;code&gt;memo&lt;/code&gt;- this is the accumulator object (this &lt;code&gt;sum&lt;/code&gt; from your standard array summimg function)&lt;/li&gt;
&lt;li&gt;&lt;code&gt;obj&lt;/code&gt; - this is the individual obj from the enumerablized container.&lt;/li&gt;
&lt;li&gt;&lt;code&gt;block&lt;/code&gt; - you should know what this is :D&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Alright, now that we know what each piece is, let&amp;#8217;s look at some examples and the refactor them with &lt;code&gt;inject&lt;/code&gt;.&lt;/p&gt;

&lt;h2&gt;Example 1&lt;/h2&gt;

&lt;p&gt;This will be a simple summing example:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;sum = 0
(1..30).each do |num|
  sum = sum + num
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now let&amp;#8217;s refactor this with &lt;code&gt;inject&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;(1..30).inject(0) do |sum, num|
  sum + num
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Here, we take the initial value of sum (0) and pass it as the argument to inject, this is the initializer.  We then take the variable name &lt;code&gt;sum&lt;/code&gt; and use it as the initial argument to the block, this is the &lt;code&gt;memo&lt;/code&gt; parameter.  &lt;code&gt;num&lt;/code&gt; then becomes the enumerated object and we continue as we did in our original &lt;code&gt;each&lt;/code&gt; method, but instead of assigning the value of the aggregation to the aggregator, we can just aggregate and ruby will take the value of the last line of the block and assign it to the memo. .&lt;/p&gt;

&lt;h2&gt;Example 2&lt;/h2&gt;

&lt;p&gt;Let&amp;#8217;s take a look at a common Rails example that I see all the time in helpers:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;ret = ""
@products.each do |prod|
  ret &amp;lt;&amp;lt; content_tag(:li, prod.title)
end
content_tag(:ul, ret)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now we refactor with &lt;code&gt;inject&lt;/code&gt;:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;lis = @products.inject("") do |ret, prod|
  ret + content_tag(:li, prod.title)
end
content_tag(:ul, lis)
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;This time we initialize inject with &amp;#8220;&amp;#8221; and we are aggregating li tags for a nice HTML list.  There is a more Ruby way to refactor this which would look like:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;content_tag(:ul, nil) do 
  @products.inject("") do |ret, prod|
    ret + content_tag(:li, prod.title)
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;Now, dont think that you can only use one-liners for your inject methods.  They are Ruby blocks, and given all the freedoms that all blocks are give.  We could do something like this if necessary:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;content_tag(:ul, nil) do 
  @products.inject("") do |ret, prod|
    if prod.active? &amp;amp;&amp;amp; prod.is_special?
      ret + content_tag(:li, prod.special_title)
    elsif prod.active?
      ret + content_tag(:li, prod.title)
    else
      ret + content_tag(:li, prod.inactive_title)
    end
  end
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;One other thing to note, &lt;code&gt;inject&lt;/code&gt;&amp;#8217;s memo object is just for aggregating, it can be used as a simple container for checks:&lt;/p&gt;

&lt;pre&gt;&lt;code&gt;success = @products.inject(true) do |ret, prod|
  ret &amp;amp;&amp;amp; prod.active?
end
&lt;/code&gt;&lt;/pre&gt;

&lt;p&gt;The above is a way to write the Enumerable#all? method.   If you replace &amp;amp;&amp;amp; with || you get the any? method.&lt;/p&gt;

&lt;p&gt;That&amp;#8217;s it for this tip, stay tuned for other refactoring tips with Ruby.&lt;/p&gt;</description>
      <pubDate>Sun, 24 Jan 2010 14:05:00 -0600</pubDate>
      <guid isPermaLink="false">urn:uuid:84837abc-e5c7-43b9-91b2-c81cb5426f44</guid>
      <author>jake</author>
      <link>http://blog.flvorful.com/articles/2010/01/24/a-simple-pattern-for-rubys-inject-method</link>
      <category>Rails</category>
      <category>rails</category>
      <category>ruby</category>
      <category>inject</category>
      <category>patterns</category>
      <category>refactoring</category>
    </item>
    <item>
      <title>Super InPlace Controls upgraded.  Now with Rails 2.3 support</title>
      <description>&lt;h2&gt;Super InPlace Controls has gone through some upgrades.&lt;/h2&gt;


	&lt;h3&gt;We&amp;#8217;ve Moved&lt;/h3&gt;


	&lt;p&gt;First and foremost, we have moved the code from google to github.&lt;/p&gt;


	&lt;p&gt;To install run&lt;/p&gt;


&lt;pre&gt;
&lt;code&gt;
script/plugin install git://github.com/flvorful/super_inplace_controls.git
&lt;/code&gt;
&lt;/pre&gt;

	&lt;h3&gt; Rails 2.3 Support&lt;/h3&gt;


	&lt;p&gt;Tested with Rails 2.3 and 2.1&lt;/p&gt;


	&lt;h3&gt; Better Jquery Support&lt;/h3&gt;


	&lt;p&gt;We have updated the code to work better with jQuery.  Now, in_place_date_selector, uses the jQuery datepicker method if available.  &lt;a href="http://github.com/aaronchi/jrails"&gt;JRails&lt;/a&gt; is required for jquery support.&lt;/p&gt;


	&lt;h3&gt; Better Validation&lt;/h3&gt;


	&lt;p&gt;Validations were a problem with &lt;span class="caps"&gt;SIPC&lt;/span&gt;, but no longer.  Now, if you dont have an error div, &lt;span class="caps"&gt;SIPC&lt;/span&gt; will skip over the rendering of the error box and just add the class &amp;#8220;fieldWithError&amp;#8221; to the proper input tag.&lt;/p&gt;


	&lt;h3&gt; Overall cleanup&lt;/h3&gt;


	&lt;p&gt;Cleaned up the code in general and made it less brittle.&lt;/p&gt;


	&lt;p&gt;Check out the &lt;a href="http://os.flvorful.com/super_in_place_controls/demo"&gt;demos&lt;/a&gt; and the &lt;a href="http://os.flvorful.com/super_in_place_controls/download"&gt;docs&lt;/a&gt; at our &lt;a href="http://os.flvorful.com/"&gt;Open Source Site&lt;/a&gt; and stay tuned for some new plugins we&amp;#8217;ve been working on.&lt;/p&gt;


	&lt;p&gt;&amp;#8212;jake&lt;/p&gt;</description>
      <pubDate>Sun, 08 Nov 2009 17:05:00 -0600</pubDate>
      <guid isPermaLink="false">urn:uuid:399e357c-07bb-4220-9f5f-79357f0dd4c6</guid>
      <author>jake</author>
      <link>http://blog.flvorful.com/articles/2009/11/08/super-inplace-controls-updated</link>
      <category>Rails</category>
      <category>superinplacecontrols</category>
      <category>plugins</category>
      <category>rails</category>
      <category>ruby</category>
      <category>jquery</category>
    </item>
    <item>
      <title>SuperInPlaceControls: A new rails plugin from Flvorful</title>
      <description>&lt;p&gt;We just finished up our newest plugin: &lt;a href="http://os.flvorful.com/super_in_place_controls"&gt;SuperInPlaceControls&lt;/a&gt;.&lt;/p&gt;


	&lt;p&gt;This is meant as a drop in replacement for the current in_place_edit_for method that was recently moved into a plugin. SuperInPlaceControls works with Rails 2.0, validations, and empty fields.&lt;/p&gt;


	&lt;p&gt;Check out the &lt;a href="http://os.flvorful.com/super_in_place_controls"&gt;SuperInPlaceControls&lt;/a&gt; page for more info, demos, examples and docs.&lt;/p&gt;


	&lt;p&gt;Have fun.&lt;/p&gt;


	&lt;p&gt;&amp;#8212;jake&lt;/p&gt;</description>
      <pubDate>Mon, 10 Dec 2007 17:12:00 -0600</pubDate>
      <guid isPermaLink="false">urn:uuid:fc402035-d012-47a0-a4ad-68baac7677bf</guid>
      <author>jake</author>
      <link>http://blog.flvorful.com/articles/2007/12/10/superinplacecontrols-a-new-rails-plugin-from-flvorful</link>
      <category>Rails</category>
      <category>ruby</category>
      <category>rails</category>
      <category>plaugins</category>
      <category>inplacecontrols</category>
      <category>ajax</category>
      <category>inplace</category>
      <trackback:ping>http://blog.flvorful.com/articles/trackback/9</trackback:ping>
    </item>
    <item>
      <title>Rescuing Ruby</title>
      <description>&lt;p&gt;Now, before anyone goes crazy, this article has nothing to do with saving ruby from something, i just couldnt think of a better title.  We will be talking about &lt;code&gt;rescue&lt;/code&gt; and some cool tricks that can be done with it.&lt;/p&gt;


	&lt;p&gt;As most of you vets know, every thing in Ruby is an object.  What most noobs dont realize is how powerful that can be and how concise your code can become.  Of course, the flip side of that problem is what i call, newbie-come-expert.  It&amp;#8217;s basically the stage in a noob&amp;#8217;s study of a language where they think they know enough to write really cool software.  What actually happens is they end up with code like this:&lt;/p&gt;


	&lt;p&gt;&lt;code&gt;@objects.map {|e| [e.id, e.title]}.sort {|a, b| a.last &amp;lt;=&amp;gt; b.last}.map {|e| e.join(" ")}.join("\n")&lt;/code&gt;&lt;/p&gt;


	&lt;p&gt;Lovely.&lt;/p&gt;


	&lt;p&gt;Dont worry noobs, everyone does it. I&amp;#8217;m still trying to undo it from some of my older code.&lt;/p&gt;


	&lt;p&gt;Anyway, my point is, sometimes Ruby&amp;#8217;s dynamicism (say that 3 times fast) can lead to messy code so use this tip wisely.&lt;/p&gt;


	&lt;p&gt;On to the actual tip.&lt;/p&gt;


	&lt;p&gt;So, like I said before, &lt;span class="caps"&gt;EVERYTHING&lt;/span&gt; in Ruby is an object, even the remains of a &lt;code&gt;rescue&lt;/code&gt; clause or an inline &lt;code&gt;rescue&lt;/code&gt; which is what we will be playing with here.&lt;/p&gt;


	&lt;p&gt;How many of you have done this:&lt;/p&gt;


	&lt;p&gt;&lt;code&gt;@person = Person.find(some_id)&lt;/code&gt;&lt;/p&gt;


	&lt;p&gt;only to get the following error:&lt;/p&gt;


	&lt;p&gt;&lt;code&gt;ActiveRecord::RecordNotFound: Couldn't find Person with ID=22&lt;/code&gt;&lt;/p&gt;


	&lt;p&gt;It&amp;#8217;s pretty annoying, mainly because this type of thing could easily happen in a live app. A user goes to find  something that isnt there.  One way around it is to have a rescue at the end of the method, but what if you have multiple finds that could throw errors?  What if you still need to be able to proceed with whatever you are doing, even if the object isnt found?&lt;/p&gt;


	&lt;p&gt;This is where inline &lt;code&gt;rescue&lt;/code&gt;&amp;#8217;s can help.&lt;/p&gt;


	&lt;p&gt;Now you can pull all of your finds together and end them with a rescue.&lt;/p&gt;


Example:
Let&amp;#8217;s say you had the following code:
&lt;pre&gt;
@person = Person.find(params[:id])
@employee = Employee.find(params[:employee_id])
&lt;/pre&gt;

	&lt;p&gt;Now, if either of these finds fail, you will get an error.  Instead of rescuing the entire method, you can resuce each statement and make the return value &lt;code&gt;nil&lt;/code&gt; and check for &lt;code&gt;nil&lt;/code&gt; like you normally would.&lt;/p&gt;


New code:
&lt;pre&gt;
@person = Person.find(params[:id]) rescue nil
@employee = Employee.find(params[:employee_id]) rescue nil
&lt;/pre&gt;

	&lt;p&gt;Now when you cant find the ID, it will rescue and just set the variables to nil and move on.&lt;/p&gt;


	&lt;p&gt;You can also set the rescues to another default datatype instead of nil.&lt;/p&gt;


	&lt;p&gt;Now, you may be saying, &amp;#8220;Wait, why would a user need to enter an id&amp;#8221;.  Well, one example is an order id, or a tracking number.  Anyway, I have run across this a couple of times and thought i&amp;#8217;d write something about it.&lt;/p&gt;


	&lt;p&gt;until next time.&lt;/p&gt;


	&lt;p&gt;&amp;#8212;jake&lt;/p&gt;</description>
      <pubDate>Sat, 11 Aug 2007 19:07:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:2b7f0456-3249-47ba-a231-1068a7d8701a</guid>
      <author>jake</author>
      <link>http://blog.flvorful.com/articles/2007/08/11/rescuing-ruby</link>
      <category>Rails</category>
      <category>rails</category>
      <category>rescue</category>
      <category>ruby</category>
      <trackback:ping>http://blog.flvorful.com/articles/trackback/2</trackback:ping>
    </item>
    <item>
      <title>New Rails Plugin - Acts As Noteable</title>
      <description>&lt;p&gt;So I was at work and I needed to add notes to multiple models in the same project (before i only had to worry about one model with notes, so it was pretty straightforward).  So i bit down and knocked out this little plugin.&lt;/p&gt;

&lt;p&gt;I borrowed heavily from Acts As Rateable by &lt;a href="http://www.juixe.com/techknow/index.php/2006/07/05/acts-as-rateable-plugin/"&gt;Juixe&lt;/a&gt;&lt;/p&gt;

    &lt;h3&gt;Installation&lt;/h3&gt;

    &lt;p&gt;Run the following command: &lt;/p&gt;

&lt;code&gt;script/plugin install http://acts-as-noteable.googlecode.com/svn/trunk/acts_as_noteable &lt;/code&gt;

    &lt;p&gt;The install will try and copy some scripts over, this works sometimes. If you get a rake error do the following:&lt;/p&gt;

    &lt;ol&gt;
    &lt;li&gt;cd vendor/plugins/acts_as_noteable&lt;/li&gt;
        &lt;li&gt;rake update_scripts&lt;/li&gt;

    &lt;/ol&gt;

    &lt;p&gt;Create a new rails migration:&lt;/p&gt;

    &lt;p&gt;&lt;code&gt;script/generate migration add_notes_to_project&lt;/code&gt;&lt;/p&gt;

    &lt;p&gt;and add the following self.up and self.down methods &lt;/p&gt;

&lt;pre&gt;
    def self.up
        create_table "notes", :force =&amp;amp;gt; true do |t|
            t.column "from", :string, :limit =&amp;amp;gt; 50, :default =&amp;amp;gt; "" 
            t.column "body", :text, :default =&amp;amp;gt; "" 
            t.column "created_at", :datetime, :null =&amp;amp;gt; false 
            t.column "noteable_id", :integer, :default =&amp;amp;gt; 0, :null =&amp;amp;gt; false 
            t.column "noteable_type", :string, :limit =&amp;amp;gt; 15, :default =&amp;amp;gt; "", :null =&amp;amp;gt; false 
        end 
    end 

    def self.down
        drop_table :notes 
    end 
 &lt;/pre&gt;

    &lt;p&gt;(one day i&amp;#8217;ll add a migration script to the plugin to automatically add this :) )&lt;/p&gt;

    &lt;p&gt;After that run &amp;#8220;rake migrate&amp;#8221; to create the table.&lt;/p&gt;

    &lt;p&gt;Now all you need to do is call acts_as_noteable in your model:&lt;/p&gt;

&lt;pre&gt;
class Model &amp;amp;lt; ActiveRecord::Base
  acts_as_noteable
end
&lt;/pre&gt;

    &lt;p&gt;Now your model is notable, but that&amp;#8217;s not all.&lt;/p&gt;

    &lt;p&gt;For only 19.95 you get a Helper method to help you create a nice form.  Ok, so i am not actually charging, but whatever.&lt;/p&gt;

    &lt;p&gt;Here&amp;#8217;s how the helper works.&lt;/p&gt;

    &lt;p&gt;In the view you want to display notes in put the following:&lt;/p&gt;

    &lt;p&gt;&lt;code&gt;&amp;amp;lt;%= display_notes(object) %&amp;amp;gt;&lt;/code&gt;&lt;/p&gt;

    &lt;p&gt;This will create a div filled with the note entries for the object and a &lt;span class="caps"&gt;&lt;span class="caps"&gt;AJAX&lt;/span&gt;&lt;/span&gt; form to add new notes to the object as well as delete notes from the object.  The add and delete methods are stored in the notes_controller.rb that gets copied over into your app/controllers directory.&lt;/p&gt;

    &lt;p&gt;The full implementation for this method is:&lt;/p&gt;

    &lt;p&gt;&lt;code&gt;&amp;amp;lt;%= display_notes(obj, partial_name = "notes/note", controller_name = "notes") %&amp;amp;gt;&lt;/code&gt;&lt;/p&gt;

    &lt;p&gt;I added the partial name and controller name in case you have multiple controllers in different folders, this way you can display notes for objects whose controllers are buried deep in a folder.&lt;/p&gt;

    &lt;p&gt;Example:  I have an &amp;#8220;admin&amp;#8221; folder for all the backend stuff and I needed a way to reference the notes controller from different places, otherwise &lt;span class="caps"&gt;&lt;span class="caps"&gt;RAILS&lt;/span&gt;&lt;/span&gt; will assume you are trying to reference a controller from the current folder your in.&lt;/p&gt;

    &lt;p&gt;After you have called display_notes, your done.&lt;/p&gt;

&lt;p&gt;Note**  This plugin has not been tested with Rails 2.0 yet&lt;p&gt;
    &lt;p&gt;peace&lt;/p&gt;
&lt;p&gt;&amp;#8212;jake&lt;/p&gt;</description>
      <pubDate>Sun, 10 Jun 2007 13:51:00 -0500</pubDate>
      <guid isPermaLink="false">urn:uuid:c73aed0a-4d25-4ec8-9581-c1b3424d74ae</guid>
      <author>jake</author>
      <link>http://blog.flvorful.com/articles/2007/06/10/new-rails-plugin-acts-as-noteable</link>
      <category>Rails</category>
      <category>noteable</category>
      <category>plugins</category>
      <category>rails</category>
      <category>ruby</category>
      <trackback:ping>http://blog.flvorful.com/articles/trackback/6</trackback:ping>
    </item>
  </channel>
</rss>
