<?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>Wojno: Tag ruby</title>
    <link>http://christopher.wojno.com/articles/tag/ruby</link>
    <language>en-us</language>
    <ttl>40</ttl>
    <description>Exploration through Code</description>
    <item>
      <title>Extending Ruby: The Sorted Array</title>
      <description>&lt;p&gt;I&amp;#8217;ve been working on my personal projects and I came across a problem with the ruby Array class. I have an array containing approximately 500 elements. I need to find each element approximately 500 times ( O(n^2) as the array search is linear ). As you can guess, it takes about 0.5 seconds for all these searches. I figured, if the linear time is 0.5, the binary search taking log_2(n) should take significantly less time to perform.&lt;/p&gt;


	&lt;h1&gt;Attempt #1: A ruby Sorted Array&lt;/h1&gt;


	&lt;p&gt;I first attempted to make a sorted array class in pure ruby. While creation of the class was easy, it was not as efficient as hoped.  As a matter of fact, according to my tests, the original ruby Array&amp;#8217;s find_index was twice as fast as mine on average. In fact, in order for my set to be as efficient as the original Array, the value being sought had to be over 4/5 the way into the array. Only after that point did my SortedArray overtake the Array in speed. Clearly, this was not the way to go.&lt;/p&gt;


	&lt;p&gt;After several attempts at re-working and simplifying the loop, I decided that the only reason the Array was so fast, was because it was written natively in C, not ruby.&lt;/p&gt;


	&lt;h1&gt;Attempt #2: A native C ruby Sorted Array&lt;/h1&gt;


	&lt;p&gt;Most of the guiding code to the Sorted Array is from the Pragmatic Ruby Programmer&amp;#8217;s Guide: Extending Ruby.&lt;/p&gt;


	&lt;h2&gt;The C-file&lt;/h2&gt;


	&lt;p&gt;First, we start with a new project tree, a-la &lt;span class="caps"&gt;SVN&lt;/span&gt; (this isn&amp;#8217;t too terribly important, but I prefer it). Next, we create the first file: sorted_array.c.&lt;/p&gt;


	&lt;p&gt;In it I included the required ruby file: ruby.h. Next, I went to the subversion repository for the Array code. I&amp;#8217;m using the 1.9.0.2 tag.&lt;/p&gt;


	&lt;p&gt;Take a good look at array.c. I&amp;#8217;s packed full of goodness. Unfortunately, I&amp;#8217;ll need to copy most of the code so that it supports all the functions we&amp;#8217;re used to with the standard Array (though, some cannot be used with this version, such as insert).&lt;/p&gt;


	&lt;p&gt;There, we now have a fully functional SortedArray that doesn&amp;#8217;t sort. It&amp;#8217;s a good start.&lt;/p&gt;


	&lt;h3&gt;Turning a normal Array into a SortedArray&lt;/h3&gt;


	&lt;p&gt;The standard Array and the SortedArray are essentially the same. The exception is that all insertions should be made in such a fashion as to preserve the ordering of the elements, that a special constructor be provided to accept un-natural sorting functions, and that searches can be optimized to take advantage of the knowledge of the arrangement of data.&lt;/p&gt;


	&lt;p&gt;The c-version of the Array has 3 major components in the data structure: length (len), ptr (the start of the array in memory), and aux. Aux has lots of things that support the array, such as the capacity. Keep these in mind when mucking with the internals.&lt;/p&gt;


	&lt;h3&gt;Remap the names&lt;/h3&gt;


	&lt;p&gt;We can&amp;#8217;t just use the code as is. Let&amp;#8217;s rename all the functions from &amp;#8220;rb_ary.&lt;pre style="display:inline;"&gt;*&lt;/pre&gt;&amp;#8221; to &amp;#8220;rb_sorted_ary_.&lt;pre style="display:inline;"&gt;*&lt;/pre&gt;&amp;#8221;. With vim, I do: :%s/rb_ary_/rb_sorted_ary_/g. Poof, all renamed.&lt;/p&gt;


	&lt;h3&gt;Enter the Constructors&lt;/h3&gt;


	&lt;p&gt;One of the constructors takes a variable argument list as the 2nd and above parameters. We need to correct this as it simply inserts values. We need to push each individual element. Yes, this will slow down the construction of these types of arrays, but again, we&amp;#8217;re banking on searching being the primary operation, not construction.&lt;/p&gt;


	&lt;p&gt;My version of array.c (1.9.0.2) looks like this:&lt;/p&gt;


&lt;pre class="code"&gt;VALUE
rb_ary_new3(long n, ...)
{
    va_list ar;
    VALUE ary;
    long i;

    ary = rb_ary_new2(n);

    va_start(ar, n);
    for (i=0; i&amp;lt;n; i++) {
    RARRAY_PTR(ary)[i] = va_arg(ar, VALUE);
    }
    va_end(ar);

    RARRAY(ary)-&amp;gt;len = n;
    return ary;
}&lt;/pre&gt;

	&lt;p&gt;It needs a little bit of changing. Let&amp;#8217;s change: &lt;span class="caps"&gt;RARRAY&lt;/span&gt;_PTR(ary) line to: &amp;#8220;rb_sorted_ary_push(ary,va_arg(ar,VALUE));&amp;#8221; That should fix it&amp;#8217;s wagon. It&amp;#8217;s a variable array, so we need to use the c-library variable argument accessors: va_arg and cast it to Ruby&amp;#8217;s &lt;span class="caps"&gt;VALUE&lt;/span&gt; type. After that, we just push it to the array, one at a time.&lt;/p&gt;


	&lt;p&gt;As you may have guessed, I&amp;#8217;ve decided to make the primary changes to push and delegating all insertion to that method. We&amp;#8217;ll get to this later, however.&lt;/p&gt;


	&lt;p&gt;Next, we tackle the new4 function. This is the &amp;#8220;copy-constructor&amp;#8221; if you&amp;#8217;re used to C++. Essentially, it is expecting an array passed in as the second parameter (&amp;#8220;elts&amp;#8221; in my version). The C-code makes a straight copy form a C-array (not a ruby Array!). However, this is not possible if the incoming array is not sorted. We need to insert them one at a time, inserting each. Originally, it looks like this:&lt;/p&gt;


&lt;pre class="code"&gt;VALUE
rb_sorted_ary_new4(long n, const VALUE *elts)
{
    VALUE ary;

    ary = rb_sorted_ary_new2(n);
    if (n &amp;gt; 0 &amp;#38;&amp;#38; elts) {
    MEMCPY(RARRAY_PTR(ary), elts, VALUE, n);
    RARRAY(ary)-&amp;gt;len = n;
    }

    return ary;
}&lt;/pre&gt;

	&lt;p&gt;The if statement is assuring that the incoming array is not empty or null (nil). That&amp;#8217;s a good check and we&amp;#8217;ll keep it. But we need to augment it. We know how long the array is, so let&amp;#8217;s just iterate through each and push the values onto the array. I threw away the &lt;span class="caps"&gt;MEMCPY&lt;/span&gt; and replaced it with:&lt;/p&gt;


&lt;pre class="code"&gt;
for(long i = 0; i &amp;lt; n; ++i) {
  rb_sorted_ary_push( ary, elts[i] );
}&lt;/pre&gt;

	&lt;p&gt;That does it for the constructors (for now, we still need to add a way to provide an unnatural sorting Proc call, but we&amp;#8217;ll come back to this later after a bit of testing).&lt;/p&gt;


	&lt;h3&gt;ary_make_* and ary_.* functions&lt;/h3&gt;


	&lt;p&gt;There are two functions that do not adhere to the rb_ary_.* syntax: ary_make_shared and ary_make_hash. Stick a &amp;#8220;sorted_&amp;#8221; in front of those definitions and in every place they are used.&lt;/p&gt;


	&lt;p&gt;Do the same with ary_.* functions (such as ary_new and ary_alloc and ary_shared_first). You can do this by simply using vim to search for &amp;#8221;\&amp;lt;ary_&amp;#8221; and it will locate any ary_ that has a space or nothing before it (starts a &amp;#8220;word&amp;#8221;).&lt;/p&gt;


	&lt;h3&gt;to_ary&lt;/h3&gt;


	&lt;p&gt;Keep them as is. I see no need to convert to a sorted array, as we may need to add a parameter to take in a custom sort function (which we&amp;#8217;re coming back to later).&lt;/p&gt;


	&lt;h3&gt;Initialize&lt;/h3&gt;


	&lt;p&gt;We now hit the initialize function. It has 4 forms:&lt;/p&gt;


	&lt;ol&gt;
	&lt;li&gt;Array.new(size=0,obj=nil)&lt;/li&gt;
		&lt;li&gt;Array.new(array)&lt;/li&gt;
		&lt;li&gt;Array.new(size) {|index| block}&lt;/li&gt;
	&lt;/ol&gt;


	&lt;p&gt;The first is easy: create an array of size, size, and then fill it with objects given in obj. This version requires no sorted, as all objects will be the same.  The second version requires a bit of changing. We need to push each value of the incoming array one at a time to ensure consistency. Jump down to rb_sorted_ary_replace.&lt;/p&gt;


	&lt;h4&gt;The Replacement Detour: before fixing initialize&lt;/h4&gt;


&lt;pre class="code"&gt;VALUE
rb_sorted_ary_replace(VALUE copy, VALUE orig)
{
    VALUE shared;
    VALUE *ptr;

    orig = to_ary(orig);
    rb_sorted_ary_modify_check(copy);
    if (copy == orig) return copy;
    shared = sorted_ary_make_shared(orig);
    if (!ARY_SHARED_P(copy)) {
    ptr = RARRAY(copy)-&amp;gt;ptr;
    xfree(ptr);
    }
    RARRAY(copy)-&amp;gt;ptr = RARRAY(orig)-&amp;gt;ptr;
    RARRAY(copy)-&amp;gt;len = RARRAY(orig)-&amp;gt;len;
    RARRAY(copy)-&amp;gt;aux.shared = shared;
    FL_SET(copy, ELTS_SHARED);

    return copy;
}&lt;/pre&gt;

	&lt;p&gt;They simply make a copy of the array&amp;#8217;s pointer and declare the source array to be shared. Since we&amp;#8217;re not sharing the array, there&amp;#8217;s no need to do this anymore, yank out the make_shared line, the line at sets the aux.shared to shared, and the FL_SET. Next, we&amp;#8217;ll yank out the pointer and length copying. Since we&amp;#8217;re replacing our contents, we need to drop the old contents. Simply drop that if-statement around the xfree(ptr); line, and that will be taken care of. We&amp;#8217;ll convert it to a for-loop, iterating through the original, don&amp;#8217;t forget to use Ruby&amp;#8217;s handy macros! To save some work, I&amp;#8217;ll re-use the existing &amp;#8220;constructor:&amp;#8221;&lt;/p&gt;


&lt;pre class="code"&gt;VALUE
rb_sorted_ary_replace(VALUE copy, VALUE orig)
{
    VALUE shared;
    VALUE *ptr;

    orig = to_ary(orig);
    rb_sorted_ary_modify_check(copy);
    if (copy == orig) return copy;
        ptr = RARRAY(copy)-&amp;gt;ptr;
        xfree(ptr);
        // create a new array
        long len = RARRAY_LEN(orig);
        if( len == 0 ) len++;
        RARRAY(copy)-&amp;gt;ptr = ALLOC_N(VALUE, len);
        RARRAY(copy)-&amp;gt;len = 0;
        RARRAY(copy)-&amp;gt;aux.capa = len;
        for( int i = 0; i &amp;lt; RARRAY_LEN(orig); ++i ) {
            rb_sorted_ary_push(copy,RARRAY(orig)-&amp;gt;ptr[i]);
        }

    return copy;
}&lt;/pre&gt;

	&lt;p&gt;OK, this is probably the most confusing part so far. Why did we throw away the shared? Ruby cheats because instead of making a true, deep copy of the array it&amp;#8217;s making a copy of, it declares the contents of the array as &amp;#8220;shared&amp;#8221; and simply copies pointers. We can&amp;#8217;t do that as we need to re-arrange our data. So that&amp;#8217;s why I yanked all the code related to sharing. So now, each object remains unlinked as far as the garbage collector is concerned. Yes, this does make things slower, and yes, does double the memory usage. But we can&amp;#8217;t modify the incoming array as it may not be intended to be sorted. So we&amp;#8217;re stuck. Because we&amp;#8217;re doing a replacement, it&amp;#8217;s best to just start from scratch. We do this by freeing up the c-array pointer, using xfree. Next, we get the length of the original array. We then use this to size-up our copy. Why do I add 1 in the case that the length is zero? Because, allocating an array of size 0 will cause C to throw a fit. So, we avoid that mess entirely by creating a starting array with 1 place to store things, but it is empty. We create the appropriately sized, internal c-array. We then set the size of the array to zero to spoof a blank array. We then set the capacity, to tell the Array that it need not resize itself when pushing the next set of items, one at a time.&lt;/p&gt;


	&lt;p&gt;When all items are added, the array will have the correct length (no longer zero, if the original wasn&amp;#8217;t empty).&lt;/p&gt;


	&lt;h4&gt;Back to Initialize to finish the last case&lt;/h4&gt;


	&lt;p&gt;Back to the &amp;#8220;initializer,&amp;#8221; we now need to take care of the strange case that uses the block to initialize the array, based on the index. We cannot assume that the values created by this block will always be in order. So, after each generation (rb_yield), we need to push them onto the array as usual.  The line looks like: &amp;#8220;rb_sorted_array_store(ary, i, rb_yeild(&lt;acronym title="i"&gt;LONG2NUM&lt;/acronym&gt;))&amp;#8221;. Simply yank that line, and the line incrementing the length (as the length will be modified by the push function). Replace those lines with: &amp;#8220;rb_ary_push(ary, rb_yield(&lt;acronym title="i"&gt;LONG2NUM&lt;/acronym&gt;));&amp;#8221; That should fix initialize.&lt;/p&gt;


	&lt;p&gt;Next, the rb_sorted_ary_s_create needs to be changed to, you guessed it, use push. Drop the length and the &lt;span class="caps"&gt;MEMCPY&lt;/span&gt; and insert the for loop, with the push call:&lt;/p&gt;


&lt;pre class="code"&gt;static VALUE
rb_sorted_ary_s_create(int argc, VALUE *argv, VALUE klass)
{
    VALUE ary = sorted_ary_alloc(klass);

    if (argc &amp;lt; 0) {
    rb_raise(rb_eArgError, "negative array size");
    }
    RARRAY(ary)-&amp;gt;ptr = ALLOC_N(VALUE, argc);
    RARRAY(ary)-&amp;gt;aux.capa = argc;
        for( int i = 0; i &amp;lt; argc; ++i ) {
            rb_sorted_ary_push(ary, argv[i] );
        }

    return ary;
}&lt;/pre&gt;

	&lt;h3&gt;Guessing an index&lt;/h3&gt;


	&lt;p&gt;Next, we need to fix up push to stop simply appending. But before that, we need to create a special function to guess an index. Why guess? Because the value may not yet exist, but if it did, this is the index where it would be located in the array. This will be the basic function for both searching, deleting, and pushing.&lt;/p&gt;


	&lt;p&gt;I&amp;#8217;ll call my new function: rb_sorted_ary_guess_index(VALUE ary, &lt;span class="caps"&gt;VALUE&lt;/span&gt; item). Not very creative, but very descriptive. Here&amp;#8217;s the problem though: we want to be able to use both natural, and unnatural sorting algorithms. And, either is fine, so long as the ordering is monotonic (goes one-way and is predictable). Before we get into that, let&amp;#8217;s just assume we&amp;#8217;re using natural ordering, for simplicity. I wrote the following code:&lt;/p&gt;


&lt;pre class="code"&gt;
&lt;/pre&gt;

	&lt;p&gt;Head up to sorted_array_alloc. Hmmm&amp;#8230;. We need to add something to our arrays! We need to store the optional sort-by block!&lt;/p&gt;


	&lt;h3&gt;The Sort-by block&lt;/h3&gt;


	&lt;p&gt;Create a new file called &amp;#8220;sorted_array.h&amp;#8221;. Create the data structure:&lt;/p&gt;


&lt;pre class="code"&gt;#include "ruby.h" 

struct RSArray {
    struct RBasic basic;
    long len;
    union {
        long capa;
        VALUE shared;
    } aux;
    VALUE *ptr;
    ID cmp;
};&lt;/pre&gt;

	&lt;p&gt;This is an exact duplicate of the RArray in ruby.h. The only exception is the additional ID *cmp, our comparison function. Be sure you&amp;#8217;ve included this structure file in the sorted_array.c file.&lt;/p&gt;


	&lt;p&gt;Back in the sorted_array.c file, make sure you cap the new cmp variable with a &lt;span class="caps"&gt;NULL&lt;/span&gt; in sorted_ary_alloc: ary-&amp;gt;cmp = &lt;span class="caps"&gt;NULL&lt;/span&gt;; Just put it under the aux.capa assignment. Now, we need to &amp;#8220;fix&amp;#8221; the sort_2 function to fall-back to the default comparison function, but to prefer a specified function if given. Let&amp;#8217;s create a class-specific sort function called: sorted_array_sort_3.&lt;/p&gt;


&lt;pre class="code"&gt;&lt;/pre&gt;</description>
      <pubDate>Mon, 23 Jun 2008 13:14:00 -0700</pubDate>
      <guid isPermaLink="false">urn:uuid:efb5c2bc-5ad2-4cf9-91c7-62dc61dc924b</guid>
      <author>Christopher Wojno</author>
      <link>http://christopher.wojno.com/articles/2008/06/23/extending-ruby-the-sorted-array</link>
      <category>Ruby Snippets</category>
      <category>ruby</category>
      <category>array</category>
      <category>c</category>
      <category>sorted</category>
      <category>extending</category>
      <category>extend</category>
      <category>native</category>
      <category>efficient</category>
      <category>lookup</category>
    </item>
    <item>
      <title>Array.valN: Working smarter with Rails, with Ruby</title>
      <description>&lt;p&gt;Rails has a powerful form builder mechanism. However, if you want to make a list of things and have the data flow back to you without involving ActiveRecord, you&amp;#8217;re in for some hurt; well, you were, unless you decide to use this module. Warning: this article is moderately advanced. I&amp;#8217;m assuming you&amp;#8217;re familiar with ActionControllers and the ActionView in my examples. If you&amp;#8217;re familiar with how to use the basics of Rails, you should probably only read the first 1/2. Read the first code block to see what my code can do. But to see why this code is useful, read on to the examples.&lt;/p&gt;


	&lt;p&gt;Say I have a set of fox phrases. Now, if a certain fox is to have a list of catch phrases, and you &lt;em&gt;don&amp;#8217;t&lt;/em&gt; want to store them in a database, you can&amp;#8217;t use Rails&amp;#8217; form helpers (text_field, hidden_field, etc.) and the params[] calls without a good deal of ugly, hack code (creating spoof instance variables to display data and creating a fake active record objects to receive that data from a form). To help beautify code, I created an additional way of accessing (setting and getting) elements in an array (valN). Behold the ArrayIterAccessors:&lt;/p&gt;


&lt;pre style="overflow:auto; clear:right;"&gt;
&amp;gt;&amp;gt; @catch_phrases = ['Addiction is like Pokemon!','Hey! There goes my pickup!','Chucky Bacon!']
=&amp;gt; ["Addiction is like Pokemon!", "Hey! There goes my pickup!", "Chucky Bacon!"]
&amp;gt;&amp;gt; @catch_phrases.val2
=&amp;gt; "Chucky Bacon!" 
&amp;gt;&amp;gt; @catch_phrases.val2 = 'Chunky Bacon! Chunky Bacon! Chunky Bacon!'
=&amp;gt; "Chunky Bacon! Chunky Bacon! Chunky Bacon!" 
&amp;gt;&amp;gt; @catch_phrases
=&amp;gt; ["Addiction is like Pokemon!", "Hey! There goes my pickup!", "Chunky Bacon! Chunky Bacon! Chunky Bacon!"]
&lt;/pre&gt;

	&lt;p&gt;&amp;#8220;Now,&amp;#8221; you say, &amp;#8220;why the heck is he not just using the []!?&amp;#8221; Well, I say, Try doing that within ActionView (rhtml template) for a text field:&lt;/p&gt;


&lt;pre&gt;
&amp;lt;%= text_field 'catch_phrases', '[0]' %&amp;gt;
&lt;/pre&gt;

	&lt;p&gt;That will fail horribly. Depending on what you set @catch_phrases to, you&amp;#8217;ll get:&lt;/p&gt;


&lt;pre&gt;
undefined method `[0]' for ['Addiction is like Pokemon!','Hey! There goes my pickup!','Chucky Bacon!']:Array
&lt;/pre&gt;

	&lt;p&gt;And that doesn&amp;#8217;t get you anywhere. So, supposin&amp;#8217; you say, oh, I dunno:&lt;/p&gt;


&lt;pre&gt;
# My special module (should be a plugin but for demonstration
# purposes, I'm defining it inline
# Skip this code for now
class CatchPhrasesController &amp;lt; ApplicationController
  module ArrayIterAccessors
  alias :old_method_missing :method_missing
  def method_missing( sym, *args, &amp;#38;block )
  sym_s = sym.to_s; t = sym_s[/\d+/]
    if t and sym_s[/\Aval\d+=?\Z/]
      if sym_s[/=\Z/]
        self[t.to_i] = args.first; return self[t.to_i]
      else
        return self[t.to_i]
      end
    else
      return old_method_missing( sym, *args, &amp;#38;block )
    end
  end
end
  # this is an action for your CatchPhrases Controller URL:
  # http://site.example.com/catch_phrases/new
  def new
    Array.send( :include, ArrayIterAccessors )
    @catch_phrases = ['Addiction is like Pokemon!','Hey! There goes my pickup!','Chucky Bacon!']
  end
end
### in your view: new.rhtml ###
&amp;lt;% @catch_phrases.each_with_index do |item,index| %&amp;gt;
&amp;lt;%= text_field 'catch_phrases', "val#{index}" %&amp;gt;
&amp;lt;% end %&amp;gt;
&lt;/pre&gt;

	&lt;p&gt;So when your view renders, you&amp;#8217;ll see 3 text fields, each with the catch phrase pre-filled (so you&amp;#8217;ll have an addiction catch phrase, a pickup catch phrase, and a chunky bacon catch phrase). You can edit them and when you submit the form, you can reconstitute your array by:&lt;/p&gt;


&lt;pre&gt;
@catch_phrases = params[:catch_phrases].keys.collect{|k| k.to_s[/\d+/] }.sort.collect{|k| params[:catch_phrases][('val'+k.to_s).to_sym] }
&lt;/pre&gt;

	&lt;p&gt;If you didn&amp;#8217;t change the catch phrases, you&amp;#8217;ll get the exact array: @catch_phrases, back. And if you &lt;em&gt;&lt;span class="caps"&gt;DID&lt;/span&gt;&lt;/em&gt; change the phrases, you&amp;#8217;ll get an array, in order, of the altered catch phrases!&lt;/p&gt;


	&lt;h2&gt;Pitfalls&lt;/h2&gt;


	&lt;ol&gt;
	&lt;li&gt;No ActiveRecord (well, I claimed that as a plus above) means: no validation. That&amp;#8217;s up to you, unless you include a validatable mixin (there are a few of those). This also means there is no way of reporting errors back automatically. I suppose I could write something later to do this.&lt;/li&gt;
		&lt;li&gt;That last line is ugly and slow.&lt;/li&gt;
		&lt;li&gt;The use example is for demonstration purposes and is awful: &lt;b&gt;&lt;span class="caps"&gt;DO NOT USE IT&lt;/span&gt;.&lt;/b&gt; That will mix the module in &lt;span class="caps"&gt;EVERY&lt;/span&gt; time you render the &amp;#8220;new&amp;#8221; action. To do this correctly take the module and the &lt;pre&gt;Array.send :include, ArrayIterAccessors&lt;/pre&gt; code out of your controller and:
	&lt;ol&gt;
	&lt;li&gt;Put it in a plugin OR&lt;/li&gt;
		&lt;li&gt;Create a new file in lib/array_iter_accessors.rb (in your Rails project) and put the module into that. Then, in your environment.rb file (at the bottom), put the &lt;pre&gt;Array.send :include, ArrayIterAccessors&lt;/pre&gt; code. That way, the mixin will only be done once.&lt;/li&gt;
	&lt;/ol&gt;&lt;/li&gt;
	&lt;/ol&gt;


	&lt;h1&gt;What I did&lt;/h1&gt;


	&lt;p&gt;I overrided the method_missing method for the Array class (then mixed it in). I scan for any method calls for methods beginning with &amp;#8220;val&amp;#8221; and ending in a number. I also parse for an &amp;#8217;=&amp;#8217; in case you&amp;#8217;d like to use it for assignment too. Then, I call the array&amp;#8217;s [] operator to access the values at the desired position. And because I&amp;#8217;m using the array&amp;#8217;s built-in operator, you&amp;#8217;ll see all the error messages and behavior you&amp;#8217;re used to seeing without my module.&lt;/p&gt;


	&lt;h2&gt;Why val?&lt;/h2&gt;


	&lt;p&gt;Because it&amp;#8217;s two letters shorter than &amp;#8220;value.&amp;#8221; What? You expected a profound reason? Sorry if this precludes your ability to keep track of your girlfriends.&lt;/p&gt;


	&lt;p&gt;You have enough here to write your own plug-in, or just to use it when you need it. Happy riding.&lt;/p&gt;</description>
      <pubDate>Mon, 13 Aug 2007 11:37:00 -0700</pubDate>
      <guid isPermaLink="false">urn:uuid:3c80d5b7-f72e-41e8-a255-9a62b0ca789a</guid>
      <author>Christopher Wojno</author>
      <link>http://christopher.wojno.com/articles/2007/08/13/array-valn-working-smarter-with-rails-with-ruby</link>
      <category>Ruby Snippets</category>
      <category>Rails Snippets</category>
      <category>ruby</category>
      <category>rails</category>
      <category>array</category>
      <category>val</category>
      <category>action</category>
      <category>view</category>
      <category>active</category>
      <category>controller</category>
      <category>module</category>
      <category>plugin</category>
    </item>
    <item>
      <title>Session of Fear</title>
      <description>&lt;p&gt;Now, before you think &amp;#8220;&lt;acronym title="Fear, Uncertainty, Disorder"&gt;FUD&lt;/acronym&gt; Time!&amp;#8221;, I preface this post with the following warning: Yes, this is a problem with not just Rails but all sessions; no, it&amp;#8217;s not unsolvable. So, in light of the bad news, there is much good news.&lt;/p&gt;


	&lt;h1&gt;The Problem&lt;/h1&gt;


	&lt;p&gt;&lt;a href="http://www.rubyonrails.org/"&gt;Rails&lt;/a&gt; applications are very useful. However, most require sessions in order to be useful. Sure, you can provide an &lt;a href="http://api.rubyonrails.org/classes/ActionWebService/Base.html"&gt;ActionWebService&lt;/a&gt; or &lt;span class="caps"&gt;REST&lt;/span&gt;-based service to not use sessions, but for the majority of user services, you&amp;#8217;re stuck with sessions.&lt;/p&gt;


	&lt;h2&gt;A Session About Sessions&lt;/h2&gt;


	&lt;p&gt;(Go ahead and skip this part if you&amp;#8217;re already familiar with how sessions work)&lt;/p&gt;


	&lt;p&gt;A session is a way a server remembers who you are (in case you didn&amp;#8217;t know). The most common way of allowing a server to ID you, without knowing who you are exactly, is by sharing a secret! Well, it&amp;#8217;s supposed to be secret and we&amp;#8217;ll come to that in a bit. When a new session is created, your session ID is generated (it&amp;#8217;s random, hopefully) and saved in the server. The id can be associated with other data, such as your name, or permissions. When you request a page, the server will give you this ID. You almost never see that ID because it&amp;#8217;s sent in the background as a &amp;#8220;cookie.&amp;#8221; You&amp;#8217;ve probably heard of these before. From now on, every time you request a page from the server, your cookie data is automatically included in the request (your web browser takes care of this) so the server can figure out who you are. Done correctly, no personally identifiable information is sent over the Web. Just your (hopefully) random ID.&lt;/p&gt;


	&lt;p&gt;Sounds good so far. But if you&amp;#8217;re not using &lt;span class="caps"&gt;HTTPS&lt;/span&gt; (SSL/TSL encryption), your secret contained in that cookie can be seen when it is first sent, and when you access any page thereafter (because you&amp;#8217;re sending it each time remember). So, if someone has access to your traffic (if you&amp;#8217;re using a shared WiFi or a hub or have a shady &lt;span class="caps"&gt;ISP&lt;/span&gt;), they can pull out your secret. Here&amp;#8217;s an old session I sniffed using a program called &lt;a href="http://www.snort.org/"&gt;snort:&lt;/a&gt;&lt;/p&gt;


&lt;pre style="overflow:auto;"&gt;
GET /javascripts/prototype.js?1186461045 HTTP/1.1..
Host: christopher.wojno.com..
User-Agent: Mozilla/5.0 (X11; U; FreeBSD i386; en-US; rv:1.8.1.6) Gecko/20070810 Firefox/2.0.0.6..
Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5..Accept-Language: en-us,en;q=0.5..
Accept-Encoding: gzip,deflate..
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7..
Keep-Alive: 300..
Connection: keep-alive..
Cookie: _session_id=db392fa5b39125fa7c1e581b9c1ec71d; is_admin=yes....
&lt;/pre&gt;

	&lt;p&gt;There it is, the last line. &amp;#8220;Cookie.&amp;#8221; So when my browser was trying to download some javascript libraries (&lt;a href="http://www.prototypejs.org/"&gt;Prototype&lt;/a&gt; is quite good), it sent my session ID. Now, the javascript doesn&amp;#8217;t care about my session ID, but it was sent any way. If someone were to see that sent over the Internet (at any point on it&amp;#8217;s way to the server), he or she could create a fake cookie with that ID and login as me without my password! (don&amp;#8217;t try it, I&amp;#8217;ve already logged out and reset the session) They could then, go into the settings and lock me out of my own system (until I change the password in the ruby console&amp;#8230; that&amp;#8217;ll show &amp;#8216;em?). In the meantime, the damage has been done and it can happen again.&lt;/p&gt;


	&lt;h1&gt;&lt;span class="caps"&gt;SSL&lt;/span&gt;!&lt;/h1&gt;


	&lt;p&gt;I won&amp;#8217;t go into &lt;span class="caps"&gt;SSL&lt;/span&gt;, but that little piece of technology has enabled credit card purchases over the Internet for years and will hopefully continue to do so for years to come. Any way, in short, it&amp;#8217;s encryption and it will encrypt cookies too!&lt;/p&gt;


	&lt;p&gt;So, we need to force rails to encrypt cookies. Not as simple as it sounds. First, you need to setup an &lt;span class="caps"&gt;SSL&lt;/span&gt; certificate on your server. Easier said than done, though, some Apache packages come with the tools to automatically generate one. For a confusing, yet interesting read, see &lt;a href="http://en.wikipedia.org/wiki/X.509"&gt;&lt;span class="caps"&gt;X509&lt;/span&gt;&lt;/a&gt; on Wikipedia.&lt;/p&gt;


	&lt;p&gt;I assume you installed your &lt;span class="caps"&gt;SSL&lt;/span&gt; certificate and have configured &lt;a href="http://www.apache.org/"&gt;Apache&lt;sup&gt;&lt;a href="#fn1"&gt;1&lt;/a&gt;&lt;/sup&gt;&lt;/a&gt; to run with &lt;span class="caps"&gt;SSL&lt;/span&gt; (or &lt;a href="http://www.lighttpd.net"&gt;lighty,&lt;/a&gt; if you&amp;#8217;re using that instead (&lt;a href="http://mongrel.rubyforge.org/"&gt;mongrel&lt;/a&gt; is not mentioned as it does not have &lt;span class="caps"&gt;SSL&lt;/span&gt;, though there is a way to use &lt;span class="caps"&gt;SSL&lt;/span&gt; and mongrel together)). If not, there are loads of &lt;a href="http://www.google.com/search?hl=en&amp;#38;client=firefox-a&amp;#38;rls=org.mozilla%3Aen-US%3Aofficial&amp;#38;hs=Kie&amp;#38;q=apache+ssl+tutorial&amp;#38;btnG=Search"&gt;tutorials.&lt;/a&gt; I warn you though, it&amp;#8217;s fairly technical.&lt;/p&gt;


	&lt;h1&gt;Hold onto your Cookies!&lt;/h1&gt;


	&lt;p&gt;So, you have &lt;span class="caps"&gt;SSL&lt;/span&gt; and a Rails application running (I&amp;#8217;m assuming). How do you tell Rails to make sure your cookies are only sent via &lt;span class="caps"&gt;SSL&lt;/span&gt;? Rails lets you specify it.&lt;/p&gt;


	&lt;h2&gt;Tell Rails to use &lt;span class="caps"&gt;SSL&lt;/span&gt; Only&lt;/h2&gt;


	&lt;p&gt;By default, Rails does &lt;em&gt;&lt;span class="caps"&gt;NOT&lt;/span&gt;&lt;/em&gt; enforce &lt;span class="caps"&gt;SSL&lt;/span&gt; on cookies or sessions (that would be frustrating for development, wouldn&amp;#8217;t it?). So you have to enable that enforcement yourself. If you want your session cookie to be sent over &lt;span class="caps"&gt;SSL&lt;/span&gt; site-wide (and generally, you do!), head into your rails application directory and open (in your favorite editor) app/controllers/application.rb  Add the following anywhere in the ApplicationController class:&lt;/p&gt;


&lt;pre&gt;
class ApplicationController &amp;lt; ActionController::Base
  session :session_key =&amp;gt; '_session_id', :session_secure =&amp;gt; true
end
&lt;/pre&gt;

	&lt;p&gt;The ApplicationController class definition should already exist, don&amp;#8217;t duplicate it. Also, make sure that session isn&amp;#8217;t already specified. If it is, the important part here is &amp;#8221;:session_secure =&amp;gt; true&amp;#8221;. Rails will now tell the browser to only send the session cookie &lt;em&gt;if&lt;/em&gt; the browser is using the https  (SSL) protocol. This feature is poorly &lt;a href="http://api.rubyonrails.org/classes/ActionController/SessionManagement/ClassMethods.html"&gt;documented&lt;/a&gt; but hopefully this will help keep your applications that you write, safe. &lt;b&gt;&lt;span class="caps"&gt;NOTE&lt;/span&gt;: You &lt;em&gt;&lt;span class="caps"&gt;MUST&lt;/span&gt;&lt;/em&gt; use &lt;span class="caps"&gt;SSL&lt;/span&gt; if you enable this or your application will become extremely forgetful&lt;/b&gt; (Who are you? What are you doing in my kitchen?!).&lt;/p&gt;


	&lt;p&gt;If you&amp;#8217;re interested in storing &lt;span class="caps"&gt;OTHER&lt;/span&gt; data (not overly recommended though due to this and another exploit) in other cookies, Rails offers &lt;a href="http://api.rubyonrails.org/classes/ActionController/Cookies.html"&gt;cookie&amp;#8212;manipulation&lt;/a&gt; (not really management, the &lt;span class="caps"&gt;API&lt;/span&gt; leaves something to be desired). You can tell individual cookies to only be sent over encrypted connections, just like the session cookie. The other exploit: if the computer is shared and the browser doesn&amp;#8217;t clear out the cookies, the next person to sit at the computer can harvest the cookie information, so don&amp;#8217;t store passwords, e-mail addresses&amp;#8230; really anything in cookies, it&amp;#8217;s just a bad idea. DO store worthless information you don&amp;#8217;t want to save in your server, such as squirrel preferences.&lt;/p&gt;


	&lt;p&gt;Admittedly, generally the odds of someone having access to your network traffic (and your cookies, no! &lt;em&gt;MY&lt;/em&gt; cookies!) directly is moderate. For the attacker to successfully pick out your cookie data from the slew of traffic wizzing by, he/she would have to be looking and looking for a specific cookie name. So make sure no one has it out for you.&lt;/p&gt;


	&lt;p&gt;I don&amp;#8217;t mean to sound down on the Rails team. Dang-fine-job I say. Cookies aren&amp;#8217;t really important and the session is cookie-based, so session security falls by the way-side. It&amp;#8217;s up to all developers to keep his or her eyes open for potential pitfalls.&lt;/p&gt;


&lt;pre&gt;
1_000.thank( Rails::DevTeam.members.collect{|m|m.email} )
&lt;/pre&gt;

	&lt;p id="fn1"&gt;&lt;sup&gt;1&lt;/sup&gt; Note: Apache doesn&amp;#8217;t know how to run Ruby code as of this writing. You need to use an Apache&amp;#8217;s mod_proxy. This will (after it&amp;#8217;s been configured) then pass the requests from Apache, to &lt;a href="http://mongrel.rubyforge.org/"&gt;mongrel&lt;/a&gt;, &lt;a href="http://www.lighttpd.net"&gt;lighty&lt;/a&gt;, or&amp;#8230; WEBrick (if you&amp;#8217;re nuts)&lt;/p&gt;</description>
      <pubDate>Fri, 10 Aug 2007 16:48:00 -0700</pubDate>
      <guid isPermaLink="false">urn:uuid:360a7ead-402b-4c87-be50-8ade85a22381</guid>
      <author>Christopher Wojno</author>
      <link>http://christopher.wojno.com/articles/2007/08/10/session-of-fear</link>
      <category>Rails Snippets</category>
      <category>ruby</category>
      <category>rails</category>
      <category>ssl</category>
      <category>cookie</category>
      <category>session</category>
      <category>secure_session</category>
      <category>security</category>
      <category>hijack</category>
    </item>
    <item>
      <title>Easy And/Or in Ruby on Rails</title>
      <description>&lt;p&gt;This missing feature of rails has really bugged me, but it&amp;#8217;s so useful.&lt;/p&gt;


	&lt;p&gt;If you have a list of words such as: apples, oranges, and bananas as an array:&lt;/p&gt;


&lt;pre&gt;
&amp;gt;&amp;gt; list = ['apples','oranges','bananas']
=&amp;gt; ["apples", "oranges", "bananas"]
&lt;/pre&gt;

	&lt;p&gt;You&amp;#8217;d like to be able to have a variable length list and still have it look correct in the view. So a smaller list:&lt;/p&gt;


&lt;pre&gt;
&amp;gt;&amp;gt; list = ['oranges','bananas']
=&amp;gt; ["oranges", "bananas"]
&lt;/pre&gt;

	&lt;p&gt;Should look like: &amp;#8220;oranges and bananas&amp;#8221;.&lt;/p&gt;


&lt;pre&gt;
&amp;gt;&amp;gt; list = ['apples','oranges','bananas']
=&amp;gt; ["apples", "oranges", "bananas"]
&amp;gt;&amp;gt; and_or_list 'and', list
=&amp;gt; "apples, oranges, and bananas" 
&amp;gt;&amp;gt; list.pop
=&amp;gt; "bananas" 
&amp;gt;&amp;gt; and_or_list 'and', list
=&amp;gt; "apples and oranges" 
&amp;gt;&amp;gt; list.pop
=&amp;gt; "oranges" 
&amp;gt;&amp;gt; and_or_list 'and', list
=&amp;gt; "apples" 
&lt;/pre&gt;

	&lt;p&gt;The following block of code will do just that:&lt;/p&gt;


&lt;pre&gt;
  def and_or_list( andor, list )
    list = list.dup
    comma = (list.size &amp;gt; 2 ? ',' : '')
    list2 = list.pop if list.size &amp;gt; 1
    s = list.join(', ')
    s &amp;lt;&amp;lt; comma+' '+andor+' ' + list2 if list2
    s
  end
&lt;/pre&gt;

	&lt;p lang="fr"&gt;Vioa!&lt;/p&gt;


	&lt;p&gt;Instant and easy listing of various things, in English. Your users will never know it&amp;#8217;s generated.&lt;/p&gt;


	&lt;p&gt;I&amp;#8217;ve wrapped it up in a neat little plug-in for you.  Just install it in your vendor/plugins directory. It will automatically be available in your views.&lt;/p&gt;


	&lt;p&gt;&lt;a href="/files/and_or_list.tar.gz"&gt;AndOrList Module&lt;/a&gt;&lt;/p&gt;</description>
      <pubDate>Mon, 06 Aug 2007 22:05:00 -0700</pubDate>
      <guid isPermaLink="false">urn:uuid:a510761c-2a6d-4604-9dd1-b0314e9217fe</guid>
      <author>Christopher Wojno</author>
      <link>http://christopher.wojno.com/articles/2007/08/06/easy-and-or-in-ruby-on-rails</link>
      <category>Rails Snippets</category>
      <category>ruby</category>
      <category>rails</category>
      <category>and</category>
      <category>or</category>
      <category>list</category>
      <category>sentence</category>
      <category>english</category>
    </item>
  </channel>
</rss>
