<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>How they Discovered Something Worth Knowing &#187; Rails</title>
	<atom:link href="http://www.silverchairsolutions.com/blog/category/rails/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.silverchairsolutions.com/blog</link>
	<description>reflections on life, technology and brownies</description>
	<lastBuildDate>Wed, 12 May 2010 14:39:21 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0</generator>
		<item>
		<title>Running HTTPS in your Rails Development Environment</title>
		<link>http://www.silverchairsolutions.com/blog/2009/09/runnning-https-in-your-rails-development-environment/</link>
		<comments>http://www.silverchairsolutions.com/blog/2009/09/runnning-https-in-your-rails-development-environment/#comments</comments>
		<pubDate>Tue, 29 Sep 2009 15:53:33 +0000</pubDate>
		<dc:creator>mhagedorn</dc:creator>
				<category><![CDATA[Rails]]></category>

		<guid isPermaLink="false">http://www.silverchairsolutions.com/blog/?p=27</guid>
		<description><![CDATA[If you are building a rails application that requires SSL for parts of your site, you are probably going to use the SSL requirement plugin. But that alone isn&#8217;t going to allow you to run your code in development. You can easily see this after you enable the SSL Requirement plugin (suddenly nothing will work). [...]]]></description>
			<content:encoded><![CDATA[<p>If you are building a rails application that requires SSL for parts of your site, you are probably going to use the <a href="http://dev.rubyonrails.org/svn/rails/plugins/ssl_requirement/">SSL requirement plugin</a>.   But that alone isn&#8217;t going to allow you to run your code in development.  You can easily see this after you enable the SSL Requirement plugin (suddenly nothing will work).   Your single mongrel instance is going to need some help in order to be able process https requests!   I wanted a simple way to allow my rails development process to continue normally and still have https protected code.</p>

<p><span id="more-27"></span>
Its not hard to set this up (ok its a bit tedious), but as <a href="http://www.subelsky.com/2007/11/testing-rails-ssl-requirements-on-your.html">Mike Subelsky</a> noted in his blog post, its not really written up elsewhere in one compact recipe.  I wanted to take a slightly different approach than what Mike took, in that I wanted to disturb the default OSX install as little as possible.  Since OSX includes an apache webserver, the idea is that you have that webserver proxy all the SSL details and then pass off control to your development instance running on localhost:3000.   The built-in instance of apache can be turned on and off in OSX by going to the Sharing control panel in your System Preferences.   If you mark the checkbox named &#8220;Web Sharing&#8221; apache is on and running, and off if the checkbox is off.   You can verify this by turning it on then browsing to http://localhost, you should see an apache screen.</p>

<h1>Step 1 &#8211; Configuring SSL Encryption</h1>

<p>Note that this recipe is a condensed version of what is found <a href="http://developer.apple.com/internet/serverside/modssl.html">here</a>, but I have cut out all the commentary. You will be using terminal for all the rest of this.  Also I am using OSX Leopard
* Shut down your local apache server
either turn off web sharing or </p>

<pre><code>sudo apachectl stop
</code></pre>

<ul>
<li><p>Create a Working Directory</p>

<p>mkdir ~/Desktop/KeyGen; cd ~/Desktop/Keygen</p></li>
<li><p>Create the RSA private key</p>

<p>openssl genrsa -des3 -out server.key 1024</p></li>
</ul>

<p>use a passphrase here as directed (and remember it <img src='http://www.silverchairsolutions.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' />  )</p>

<ul>
<li><p>Create the CSR (Certificate Signing Request)</p>

<p>openssl req -new -key server.key -out server.csr </p></li>
</ul>

<p>This signing request you will sign yourself (for development only of course).  For this CSR enter &#8217;127.0.0.1&#8242; for the prompted &#8220;Common Name &#8211; i.e. for the appropriate server&#8221;</p>

<ul>
<li><p>Create a Certificate Authority (CA) to sign the key</p>

<pre><code>openssl genrsa -des3 -out ca.key 1024
</code></pre></li>
</ul>

<p>use a passphrase here again</p>

<ul>
<li><p>Create a self-signed CA certificate using the key you just made</p>

<p>openssl req -new -x509 -days 365 -key ca.key -out ca.crt</p></li>
</ul>

<p>in the &#8220;Common Name&#8221; field enter your name, because you are the dummy certificate authority and you are the one signing it.</p>

<ul>
<li><p>Download the latest mod_ssl distribution
It can be found <a href="http://www.modssl.org/">here</a>.  Look in the pkg.contrib subdirectory and copy the file sign.sh to your working directory. Then you have to make the file executable, and sign the csr.</p>

<p>chmod +x sign.sh ;./sign.sh server.csr</p></li>
</ul>

<p>Enter &#8216;yes&#8217; for all the prompts, and you will have a directory full of files, representing the signed csr.</p>

<ul>
<li><p>Put the signed files where apache can use them</p>

<p>sudo mkdir /etc/apache2/ssl.key</p></li>
</ul>

<p>Move all of the contents of your working directory to the ssl.key directory you just made.</p>

<pre><code>sudo cp -r * /etc/apache2/ssl.key/
</code></pre>

<ul>
<li><p>Remove the passphrase from the server key (DONT DO THIS FOR A PRODUCTION SYSTEM)</p>

<pre><code>cd /etc/httpd/ssl.key
sudo cp server.key server.key.original
sudo openssl rsa -in server.key.original -out server.key
</code></pre></li>
</ul>

<h1>Step 2 &#8211; Modify the Apache config files</h1>

<ul>
<li><p>First, back up the existing apache config file for safety</p>

<p>cd /etc/apache2
sudo cp httpd.conf httpd.conf.backup</p></li>
<li><p>Then use your favorite editor to enable the appropriate LoadModule statements.   (you are going to have to use sudo (&#8216;sudo vi&#8217;) to open this file in order to save it).  Search for a line that looks like this:</p>

<p>LoadModule ssl<em>module libexec/apache2/mod</em>ssl.so</p></li>
</ul>

<p>and make sure that the # at the beginning of the line is not there (i.e. the comment indication), if it is there remove it.  Likewise remove # from this line a bit farther down</p>

<pre><code>Include /private/etc/apache2/extra/httpd-vhosts.conf
</code></pre>

<p>and this&#8230;</p>

<pre><code>Include /private/etc/apache2/extra/httpd-ssl.conf
</code></pre>

<ul>
<li><p>Back up your extra/httpd-ssl.conf</p>

<p>sudo cp httpd-ssl.conf httpd-ssl.conf.original</p></li>
<li><p>Comment out the following line by putting a # at the beginning of it (we are putting this setting in the httpd-vhosts.conf file)</p>

<p>Listen 443</p></li>
<li><p>Remove the Virtual Host</p></li>
</ul>

<p>Then remove all the lines starting at</p>

<pre><code>    &lt;VirtualHost _default_:443&gt;
</code></pre>

<p>and ending at</p>

<pre><code>    &lt;/VirtualHost&gt; 
</code></pre>

<p>We are going to define all our virtual host stuff in the httpd-vhosts.conf file, so its not needed here.</p>

<ul>
<li><p>Back up your extra/httpd-vhosts.conf and edit it</p>

<p>sudo cp httpd-vhosts.conf httpd-vhosts.conf.original</p></li>
</ul>

<p>I pretty much deleted everything in my vhosts file and replaced it with the following content</p>

<pre><code>Listen 443

SSLCertificateFile /etc/apache2/ssl.key/server.crt
SSLCertificateKeyFile /etc/apache2/ssl.key/server.key

CustomLog logs/ssl_request_log  "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"

&lt;VirtualHost *:80&gt;
 ServerName localhost
 ServerAlias 127.0.0.1

 ProxyPass / http://localhost:3000/
 ProxyPassReverse / http://localhost:3000
 ProxyPreserveHost on
&lt;/VirtualHost&gt;

&lt;VirtualHost *:443&gt;
 SSLEngine On
 ServerName localhost
 ServerAlias 127.0.0.1

 ProxyPass / http://localhost:3000/
 ProxyPassReverse / http://localhost:3000
 ProxyPreserveHost on
 RequestHeader set X_FORWARDED_PROTO 'https'
&lt;/VirtualHost&gt;
</code></pre>

<p>And thats it.  Go to your Sharing control panel and turn on Web Sharing.  You should see https requests being forwarded correctly to your rails application (assuming that its listening on the default mongrel port of 3000).</p>
]]></content:encoded>
			<wfw:commentRss>http://www.silverchairsolutions.com/blog/2009/09/runnning-https-in-your-rails-development-environment/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Announcing the migrate_war Rails plugin</title>
		<link>http://www.silverchairsolutions.com/blog/2008/04/announcing-the-migrate_war-rails-plugin/</link>
		<comments>http://www.silverchairsolutions.com/blog/2008/04/announcing-the-migrate_war-rails-plugin/#comments</comments>
		<pubDate>Thu, 17 Apr 2008 16:32:00 +0000</pubDate>
		<dc:creator>mhagedorn</dc:creator>
				<category><![CDATA[Rails]]></category>

		<guid isPermaLink="false">http://www.silverchairsolutions.com/blog/?p=26</guid>
		<description><![CDATA[The MigrateWar Rails plugin makes it easy to create database schema on deployment machines when you deploy via JRuby/War Files. This is especially helpful on Windows machines, where you cannot use Capistrano easily. Capistrano is a powerful deployment tool that is considered &#8216;state of the practice&#8217; by anyone deploying Rails applications to Unixy type systems. [...]]]></description>
			<content:encoded><![CDATA[<p>The MigrateWar Rails plugin makes it easy to create database schema on deployment machines when you deploy via JRuby/War Files.  This is especially helpful on Windows machines, where you cannot use Capistrano easily. </p>

<p>Capistrano is a powerful deployment tool that is considered &#8216;state of the practice&#8217; by anyone deploying Rails applications to Unixy type systems.  But what about if you need some of that same Capistrano fu on a windows server.   Can it be done?   In my case I really needed a way to build my
database schema on the deployment target as soon as the application was deployed (cap deploy with migrations basically).   This isnt such an 
easy thing to do as I found.    I was going to deploy via JRuby/Goldspike in a War file format (the standard java deployment package), so I dusted off my arcane Java knowledge and came up with a solution to load the schema.rb file as soon as the war file loads.  Read on for details.</p>

<p><span id="more-26"></span></p>

<p>The trick here, was that I needed the &#8220;migrate to current&#8221; process to run only once, when the Rails application loads.  When you deploy the web application via the Goldspike Plugin, you end up with a pretty standard Java Web Application  WAR file (i.e. Web ARchive).   WAR files have a very well defined set of hooks for startup and teardown, which of course would directly correspond to the startup of the Rails application that we are deploying inside of that WAR file.  So the basic trick, is to leverage the startup hook of the WAR file (In Javaland this is called a Context) and run the appropriate logic for creating database schema on the deployment box.    You could of course do arbitrary other things as well, but thats a talk for another time.</p>

<p>We want to do this in such a way that we are writing a minimum of Java code, and pushing most of the work of doing this off to Ruby.  The first thing we have to do is create the Java class which runs when the Context loads (i.e. the Rails application).   This is done by creating a ServletContextListener, an interface in Java.   Here is an excerpt of the class I wrote (showing only the important bits)</p>

<p>`  </p>

<pre><code>    public void contextInitialized(ServletContextEvent event) {
  try {
      final ServletContext context = event.getServletContext();
      // create the pool
      initiallizeJrubyEnvironment(context);

      //this is defined in the web.xml
      commandFile = context.getInitParameter("command-file");


      System.out.println("Entering: MigratorContentListener.contextIntialized \n");

      thread = new Thread(new Runnable() {

          public void run() {
              try {
                  // wait for a little while before starting the task
                  // this allow the app server to start serving requests before initializing all tasks
                  Thread.sleep(100);


                  runOnce(context);
                  System.out.println("Exiting: MigratorContentListener.contextIntialized \n");
              } catch (InterruptedException e) {
                  // break out of loop
              } catch (Exception e) {
                  context.log("Could not start " + commandFile, e);
              }
          }
      });
      thread.start();
  } catch (ServletException ex) {
      Logger.getLogger(MigratorContextListener.class.getName()).log(Level.SEVERE, null, ex);
  }}'
</code></pre>

<p>&#8216;<br />
    private void runOnce(ServletContext context) throws Exception {</p>

<pre><code>    try {
        String rootDir = context.getRealPath("");

        Ruby runtime = null;
        try {

            String script = readFileAsString(rootDir + "/" + commandFile);
            context.log("executing "+script);
            runtime = (Ruby) getRuntimePool().borrowObject();
            runtimeApi.eval(runtime,"ENV['RAILS_ROOT'] = '" + rootDir + "'");
            runtimeApi.eval(runtime, script);
            getRuntimePool().returnObject(runtime);
        } catch (Exception e) {
           context.log("Could not execute: " + commandFile, e);
            getRuntimePool().invalidateObject(runtime);
          context.log(commandFile + " returning JRuby runtime to pool and will restart in 15 minutes.");
            try {
                Thread.sleep(FIFTEEN_MINUTES_IN_MILLIS);
            } catch (InterruptedException ex) {
            // can't do much here ...
            }
        }


    } catch (Exception e) {
        e.printStackTrace();
        context.log("Could not execute: " + commandFile, e);
    }
}`
</code></pre>

<p>The J2EE application server will call the contextInitiallized method shown above when the WAR file loads.  In the 4th line of that method, notice that I get the name of the ruby file to run, its passed in via a parameter defined in the web.xml file.   More on that later.    Basically this class executes the &#8220;runOnce&#8221; method one time, in a separate thread, as soon as the context loads.   Really all the runOnce method does is pass the name of the method to run to the Ruby runtime that has been set up  via the magic of JRuby.   </p>

<p>In order to get this file to get loaded by the Application Server, you need to make two entries in the web.xml file.   The first one, which tells it to attach a listener to the Context, looks like this  </p>

<p><code>&lt;listener&gt;
   &lt;listener-class&gt;org.jruby.webapp.MigratorContextListener&lt;/listener-class&gt;
 &lt;/listener&gt;</code></p>

<p>where the MigratorContextListener is the Java class that contains the logic listed above.  The second entry that you need to put into the web.xml file is what the ruby file is named that you want executed.   Here is that entry  </p>

<p><code>&lt;context-param&gt;
    &lt;param-name&gt;command-file&lt;/param-name&gt;
    &lt;param-value&gt;migrator.rb&lt;/param-value&gt;
    &lt;description&gt;Run this file to execute an initial migration (for deployment to new platforms)&lt;/description&gt;
&lt;/context-param&gt;</code></p>

<p>The migrator.rb file, the one that gets executed on startup (and found in the root of the application), looks like this  </p>

<p><code>load('db/schema.rb')</code></p>

<p>Once this executes, the production database indicated in the database.yml will get the schema.rb file applied to it.  It would have been much cooler to actually run a migration, but by the time you deploy to production, your schema has probably settled down anyway, so applying the schema.rb file is probably sufficient.  I guess the bigger point is, you can do arbitrary things at install time with this.</p>

<p>I bundled all of this up into a plugin called &#8220;migrate_war&#8221;, one of the things this plugin includes is a jar file which contains the ContextListener, you have to tell the GoldSpike plugin about this jar file so that it includes it in the WAR file it generates.   To do this edit the config/war.rb file and add this to the end:  </p>

<p><code>include_library 'migrator-rails' , '0.9'</code></p>

<p>When you install the plugin, it will copy that jar to lib/java and the include_library command will find it there and pull it into the generate WAR file.</p>

<p>Once you have installed the plugin and made the include_library addition shown above, go ahead and generate your WAR file using Goldspike.</p>

<p>After that finishes you can edit the web.xml file found in WEB-INF/web.xml (Goldspike generates the WEB-INF and everything below it) with the xml edits shown above (for the listener, and the command-file).  Then you need to run it again to generate the WAR file with the modified web.xml included (if the WEB-INF directory already exists the Goldspike plugin won&#8217;t clobber this directory unless you tell it to, so its cool to edit these files before generating again, Goldspike will use whats in WEB-INF).</p>

<p>You can install the plugin by entering  </p>

<p><code>script/plugin install http://svn.silverchairsolutions.com/migrate_war/</code>. </p>

<p>Hope this helps someone!</p>

<p>Update:  Its important to note that this will apply the schema.rb file directly to your database.  This will blow away the schema contained within (and any data found there).  So if you need to save the data, you should export it then reimport it after the schema gets built.  It would be much cooler if migrations were run on this.  Anyone care to try?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.silverchairsolutions.com/blog/2008/04/announcing-the-migrate_war-rails-plugin/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>I&#8217;m an Author!</title>
		<link>http://www.silverchairsolutions.com/blog/2008/04/im-an-author/</link>
		<comments>http://www.silverchairsolutions.com/blog/2008/04/im-an-author/#comments</comments>
		<pubDate>Sat, 12 Apr 2008 14:35:05 +0000</pubDate>
		<dc:creator>mhagedorn</dc:creator>
				<category><![CDATA[Rails]]></category>

		<guid isPermaLink="false">http://www.silverchairsolutions.com/blog/?p=24</guid>
		<description><![CDATA[Ok its been awhile since this occurred, but I would be remiss if I didn&#8217;t mention that I have been included as one of the authors of the Pragmatic Studio&#8217;s Advanced Rails Recipes Book. I contributed a chapter on creating Wizards. You can check it out here. Basically I leveraged actsasstate_machine to pull this off. [...]]]></description>
			<content:encoded><![CDATA[<p>Ok its been awhile since this occurred, but I would be remiss if I didn&#8217;t mention that I have been included as one of the authors of the Pragmatic Studio&#8217;s Advanced Rails Recipes Book.   I contributed a chapter on creating Wizards.   You can check it out <a href="http://www.pragprog.com/titles/fr_arr" title="Advanced Rails Recipes">here</a>.  Basically I leveraged acts<em>as</em>state_machine to pull this off.  Check it out!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.silverchairsolutions.com/blog/2008/04/im-an-author/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>State Transition Diagrams for acts_as_state_machine</title>
		<link>http://www.silverchairsolutions.com/blog/2008/03/state-transition-diagrams-for-acts_as_state_machine/</link>
		<comments>http://www.silverchairsolutions.com/blog/2008/03/state-transition-diagrams-for-acts_as_state_machine/#comments</comments>
		<pubDate>Wed, 05 Mar 2008 22:31:49 +0000</pubDate>
		<dc:creator>mhagedorn</dc:creator>
				<category><![CDATA[Rails]]></category>

		<guid isPermaLink="false">http://www.silverchairsolutions.com/blog/?p=21</guid>
		<description><![CDATA[Lately I have been using the wonderful acts_as_state_machine plugin for lots of cool stuff in my rails applications. The problem that I have run into though, is visualizing the state transitions that I have created. Typically, when I first learned about state machines back in Electrical Engineering days, we drew cool diagrams with bubbles to [...]]]></description>
			<content:encoded><![CDATA[<p>Lately I have been using the wonderful <code>acts_as_state_machine</code> plugin for lots of cool stuff in my rails applications.   The problem that I have run into though, is visualizing the state transitions that I have created.  Typically, when I first learned about state machines back in Electrical Engineering days, we drew cool diagrams with bubbles to represent the states and arrows to show the state transitions (a.k.a state transition diagrams).  I have found these to be very helpful.   But I wanted to a way to automatically create these.</p>

<p><span id="more-21"></span></p>

<p>My first problem was, how do I dynamically create graphs?   This was solved when I found out about this:
<a href="http://www.graphviz.org" title="graphviz">Graphviz</a>, an open source graph visualization language that many software packages understand.   There are stand-alone graph readers available as well as tools like OmniGraffle for the mac which can read this format.  We will create our diagrams in this format (.dot).  </p>

<p>My solution was inspired by Dave Thomas and his <em>annotate_models</em> plugin.   I created a plugin that is triggered as a rake task, i.e. <code>rake annotate_states</code>   I used Dave&#8217;s code to guide me on how to step through all the model classes, then I added additional logic to filter out all model classes that didnt use acts<em>as</em>state_machine.   I then introspected on the remaining list and got a list of states and transitions so that I could build the diagram.</p>

<p>You can install the plugin in the usual way, navigate to the root of your application and type <code>script/plugin install http://svn.silverchairsolutions.com/annotate_states</code>.   </p>

<p>After installing the plugin (and checking that it lists as a rake task by typing rake -T) you can create the .dot files for your application by typing <code>rake annotate_states</code>.   Each model file in your application that uses <code>acts_as_state_machine</code> should produce a state transition diagram in the root of your application.</p>

<p>Hope you enjoy it!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.silverchairsolutions.com/blog/2008/03/state-transition-diagrams-for-acts_as_state_machine/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>ActiveScaffold &amp; Streamlined Woes</title>
		<link>http://www.silverchairsolutions.com/blog/2007/10/activescaffold-streamlined-woes/</link>
		<comments>http://www.silverchairsolutions.com/blog/2007/10/activescaffold-streamlined-woes/#comments</comments>
		<pubDate>Mon, 08 Oct 2007 15:34:09 +0000</pubDate>
		<dc:creator>mhagedorn</dc:creator>
				<category><![CDATA[Rails]]></category>

		<guid isPermaLink="false">http://www.silverchairsolutions.com/blog/?p=17</guid>
		<description><![CDATA[Found an interesting gotcha while trying out some of the new &#8220;User Interface in a Can&#8221; frameworks. If you use the new hasmany :through style declaration (rather than the old way hasandbelongsto_many) for modeling your many to many relationships in ActiveRecord, then that relationship cannot be editable in these frameworks. What happens is that a [...]]]></description>
			<content:encoded><![CDATA[<p>Found an interesting gotcha while trying out some of the new &#8220;User Interface in a Can&#8221; frameworks.   If you use the new has<em>many :through style declaration (rather than the old way has</em>and<em>belongs</em>to_many)
for modeling your many to many relationships in ActiveRecord, then that relationship cannot be editable in these frameworks.  What happens is that a relationship
is inferred, but since that relationship is read-only, a gui is generated which cannot edit that relationship.  Which in non-geek speak means <em>WORTHLESS</em>.
Since I was on a tight time budget on a project, I had to do something, so I am in the process of converting back to HABTM, which both frameworks
happily use.  I haven&#8217;t had a moment to grok why this is.  But something about the existence of the :through class messes up introspecting the relationships.
I am hoping this isn&#8217;t too much of a limitation, because I like overall the GUI&#8217;s that are produced.   Furthermore in my work at least I haven&#8217;t had to utilize
the power of a full-fledged join model in the middle, so I am hoping that this wont mess me up too much.</p>

<p>Has anyone else run into this?</p>
]]></content:encoded>
			<wfw:commentRss>http://www.silverchairsolutions.com/blog/2007/10/activescaffold-streamlined-woes/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Two Interesting Things About ActiveRecord Validations</title>
		<link>http://www.silverchairsolutions.com/blog/2007/10/two-interesting-things-about-activerecord-validations/</link>
		<comments>http://www.silverchairsolutions.com/blog/2007/10/two-interesting-things-about-activerecord-validations/#comments</comments>
		<pubDate>Thu, 04 Oct 2007 17:29:04 +0000</pubDate>
		<dc:creator>mhagedorn</dc:creator>
				<category><![CDATA[Rails]]></category>

		<guid isPermaLink="false">http://www.silverchairsolutions.com/blog/?p=16</guid>
		<description><![CDATA[You know how people always tell you &#8220;once you know how this works, you can break the rules when you need&#8221;. I had to apply this maxim recently. I had a situation where I needed to create new records on a form (so they would display as lineitems), but needed to defer validating these items [...]]]></description>
			<content:encoded><![CDATA[<p>You know how people always tell you &#8220;once you know how this works, you can break the rules when you need&#8221;.  I had to apply this maxim recently.
I had a situation where I needed to create new records on a form (so they would display as lineitems), but needed to defer validating these items until later.  (In my case it was time sheet entries, but it doesnt really matter.)   I struggled with how to do this until I stumbled on these two gems of knowledge. (which I probably should have remembered anyway)</p>

<p><em>ActiveRecord#save(false)</em>
you can force active record to save and ignore validation errors</p>

<p><em>ActiveRecord#update_attribute</em>
This does the same thing as above, but on a per attribute basis</p>

<p>Very handy.   And yes.. I know that this is &#8220;breaking the rules&#8221; because I am skipping validation.  But in this particular case.. it makes sense</p>
]]></content:encoded>
			<wfw:commentRss>http://www.silverchairsolutions.com/blog/2007/10/two-interesting-things-about-activerecord-validations/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Installing attachment_fu</title>
		<link>http://www.silverchairsolutions.com/blog/2007/09/installing-attachment_fu/</link>
		<comments>http://www.silverchairsolutions.com/blog/2007/09/installing-attachment_fu/#comments</comments>
		<pubDate>Wed, 12 Sep 2007 13:08:10 +0000</pubDate>
		<dc:creator>mhagedorn</dc:creator>
				<category><![CDATA[Rails]]></category>

		<guid isPermaLink="false">http://www.silverchairsolutions.com/blog/?p=13</guid>
		<description><![CDATA[After hearing Rick Olsen&#8217;s talk at the LSRC, I simply had to try the attachment_fu plugin that he wrote to handle image uploads. Strictly speaking, this plugin doesn&#8217;t have any other external requirements. However (there always is a however isn&#8217;t there?) if you are going to take advantage of automatic thumbnails or resizing or the [...]]]></description>
			<content:encoded><![CDATA[<p>After hearing Rick Olsen&#8217;s talk at the <a href="http://www.lonestarrubyconf.com">LSRC</a>, I simply had to try the <em>attachment_fu</em> plugin that he wrote
 to handle image uploads. Strictly speaking, this plugin doesn&#8217;t have any other external requirements.  However (there always is a however isn&#8217;t there?)
 if you are going to take advantage of automatic thumbnails or resizing or the like, you need some kind of backing image library to make it all work.
  This of course caused me much consternation after fighting with osx to install rmagic.  I had little desire to repeat that episode.   I referenced Mike Clark&#8217;s 
<a href="http://clarkware.com/cgi/blosxom/2007/02/24">blog entry</a> about installing attachment_fu, and he referenced and recommended installing 
<a href="http://seattlerb.rubyforge.org/ImageScience.html">ImageScience</a> 
to handle all the image processing duties.   The instructions had a few bumps in them (notably installing FreeImage), and I wanted to make it easier on folks who follow after me,
so I wrote a script to handle all of the downloading and compiling drudgery to get ImageScience up and running.  I am running my systems on OSX, but
the script should work just fine due to the makefiles being cross platform.    <a href="http://www.silverchairsolutions.com/files/im_sci_inst.sh">Download</a> it and run it!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.silverchairsolutions.com/blog/2007/09/installing-attachment_fu/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Memcached and OSX</title>
		<link>http://www.silverchairsolutions.com/blog/2007/07/memcached-and-osx/</link>
		<comments>http://www.silverchairsolutions.com/blog/2007/07/memcached-and-osx/#comments</comments>
		<pubDate>Thu, 19 Jul 2007 11:44:04 +0000</pubDate>
		<dc:creator>mhagedorn</dc:creator>
				<category><![CDATA[Memcached]]></category>
		<category><![CDATA[Rails]]></category>

		<guid isPermaLink="false">http://www.silverchairsolutions.com/blog/?p=4</guid>
		<description><![CDATA[I was working on part of my soon to be launched rails project, snowballr, and found part of one of my processes to be particular expensive from a computational perspective. Being a bright sort of chap, my immediate reaction was &#8220;cache the results&#8221; and since I come from a proud lineage of Java developers I [...]]]></description>
			<content:encoded><![CDATA[<p>I was working on part of my soon to be launched rails project,  <a href="http://www.snoballr.com">snowballr</a>, and found part of one of my processes to be particular expensive from a computational perspective.    Being a bright sort of chap, my immediate reaction was &#8220;cache the results&#8221; and since I come from a proud lineage of Java developers I bravely set off to create my own caching scheme.  This of course turned out to be a really bad case of the &#8220;Not Invented Here&#8221; syndrome which of course my enterprisy roots have tended to foster <img src='http://www.silverchairsolutions.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .   I looked around for other solutions, and found the tried and true <strong>memcached</strong>  solution that has been used by tons of people to accomplish the same thing. <strong>Memcached</strong> (pronounced mem-cache-dee) is a distributed caching framework that alleviates database load. It was originally developed for the website LiveJournal.com.   My main reason for not considering that before, is  that it can start to seem like you need a million moving pieces of code all working together in order to get a rails application properly running (you know the drill, mongrel, pound.. rmagick &#8211;YIKES).  I just didn&#8217;t want to add to the complexity.    </p>

<p>Furthermore I was hosting at a shared host, and things like <strong>memcached</strong> just aren&#8217;t going to happen.  I had already got bitten once by assuming distributed ruby, drb would run at my shared host, and when it came to deploy time I was in for a rude awakening.   Since then I have set up a virtual server at SliceHost, and so I control whatever is on that box.  Memcached suddenly looked like a viable solution.</p>

<p>Here is what I did to set it up on my MacBook Pro.   Since OSX by default has some issues with some of the binary releases available, Geoffrey Grosenbach has written a script which downloads, patches and compiles all the right stuff.   Get the script <a href="http://www.topfunky.net/svn/shovel/memcached/install-memcached.sh">here</a>.     This script will create binaries in /usr/local/bin, so make sure that is in your path.  </p>

<p>after downloading the script, cd to a directory of your choice (I created a directory &#8220;memcached&#8221; in my development folder) and run the script.  It should happily churn while you are getting your coffee.</p>

<p>At the conclusion of the script, you need to edit your .bash<em>profile to include EVENT</em>NOKQUEUE=1.  I am not sure what voodo this does, but its required <img src='http://www.silverchairsolutions.com/blog/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .  Go ahead and pull that configuration into your current environment by entering
<code>$ source  ~/.bash_profile</code></p>

<p>Next you&#8217;ll need to install the Ruby memcached client.  This allows the rails application to put and get things from the cache.  Install it with:</p>

<p><code>$ sudo gem install memcache-client</code></p>

<p>Now that the client and server is installed, you can start doing some basic testing.  To start the server type:</p>

<p><code>$ memcached -vv</code></p>

<p>( the -vv means verbose output)</p>

<p>Once the server is up and running, you have to tell your rails application how to find your distributed cache.  On both my development and production environments, my cache will be running on localhost, so my configuration won&#8217;t change when I deploy.  For that reason I will put the necessary rails configuration information in the generic <em>config/environment.rb</em>
 file rather than the more specific <em>config/environments/development.rb</em> (or <em>production.rb</em>).  Configure the memcached client by adding the following lines to  the end of environment.rb:</p>

<p><code>CACHE = MemCache.new :namespace => "my<em>application",
                     :c</em>threshold => 10000,
                     :compression => true,
                     :debug => false,
                     :readonly => false,
                     :urlencode => false</p>

<p>CACHE.servers = '127.0.0.1:11211'
ActionController::Base.session<em>options[:expires] = 1800
ActionController::Base.session</em>options[:cache] = CACHE</code></p>

<p>(you could of course have run the memcached server on any arbitrary address, and included that address  in the servers parameter shown above)</p>

<p>Now that this information is entered, you can test the basic operation of the cache from the rails console and observe inbound requests from the memcached process you started earlier.  Enter the following from the rails console:</p>

<p><code>$ script/console
Loading development environment</p>

<blockquote>
  <blockquote>
    <p>CACHE["test"] = "my cool cached info"
    =>"my cool cached info"
    CACHE["test"]
    =>"my cool cached info"
    CACHE.delete "test"
    =>"DELETED\r\n"
    CACHE["test"]
    =>nil</code></p>
  </blockquote>
</blockquote>

<p>and thats pretty much it!   To use it in your controllers or models simply put objects in the cache using CACHE[<key>] = object or CACHE[<key>] to retrieve.  </p>
]]></content:encoded>
			<wfw:commentRss>http://www.silverchairsolutions.com/blog/2007/07/memcached-and-osx/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
