<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/rss2full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><rss 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:feedburner="http://rssnamespace.org/feedburner/ext/1.0" version="2.0">

<channel>
	<title>LRBlog</title>
	
	<link>http://blog.lrdesign.com</link>
	<description>Logical Reality Design: Web Design and Software Development</description>
	<pubDate>Mon, 22 Jun 2009 23:01:29 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.7.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" href="http://feeds.feedburner.com/LRBlog" type="application/rss+xml" /><feedburner:browserFriendly></feedburner:browserFriendly><item>
		<title>Rails fixture strings that are all numbers</title>
		<link>http://blog.lrdesign.com/2009/06/rails-fixture-strings-that-are-all-numbers/</link>
		<comments>http://blog.lrdesign.com/2009/06/rails-fixture-strings-that-are-all-numbers/#comments</comments>
		<pubDate>Mon, 22 Jun 2009 23:00:51 +0000</pubDate>
		<dc:creator>Evan</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.lrdesign.com/?p=69</guid>
		<description><![CDATA[I ran into this one today:  If you need to specify a string in a YAML file (fixtures or the like) but that string is all digits, put it in quotes.
The problem YAML file looked like this:
spec/fixtures/people.yml (broken)

one:
&#160;&#160;&#160;&#160;funky_database_id:&#160;&#160;0000012345

two:
&#160;&#160;&#160;&#160;funky_database_id:&#160;&#160;0000012346

The trouble with this is that yaml interprets those values as integers, not strings, and Person#funky_database_id is [...]]]></description>
			<content:encoded><![CDATA[<p>I ran into this one today:  If you need to specify a string in a YAML file (fixtures or the like) but that string is all digits, put it in quotes.</p>
<p>The problem YAML file looked like this:</p>
<h3>spec/fixtures/people.yml (broken)</h3>
<p><pre><code>
one:
&nbsp;&nbsp;&nbsp;&nbsp;funky_database_id:&nbsp;&nbsp;0000012345

two:
&nbsp;&nbsp;&nbsp;&nbsp;funky_database_id:&nbsp;&nbsp;0000012346
</code></pre></p>
<p>The trouble with this is that yaml interprets those values as integers, not strings, and Person#funky_database_id is a string column.   So Ruby conveniently loads the value as an integer and runs to_s on it before inserting.  Worse, because these start with 0, they get translated from octal.   So <code>people(:one).funky_database_id</code> comes out "5349".  Definitely not what I wanted. </p>
<p>This works as expected:</p>
<h3>spec/fixtures/people.yml (fixed)</h3>
<p><pre><code>
one:
&nbsp;&nbsp;&nbsp;&nbsp;funky_database_id:&nbsp;&nbsp;&quot;0000012345&quot;

two:
&nbsp;&nbsp;&nbsp;&nbsp;funky_database_id:&nbsp;&nbsp;&quot;0000012346&quot;
</code></pre></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lrdesign.com/2009/06/rails-fixture-strings-that-are-all-numbers/feed/</wfw:commentRss>
		</item>
		<item>
		<title>New York Times article about UniThrive</title>
		<link>http://blog.lrdesign.com/2009/06/new-york-times-article-about-unithrive/</link>
		<comments>http://blog.lrdesign.com/2009/06/new-york-times-article-about-unithrive/#comments</comments>
		<pubDate>Sat, 13 Jun 2009 16:34:16 +0000</pubDate>
		<dc:creator>Evan</dc:creator>
		
		<category><![CDATA[Projects]]></category>

		<category><![CDATA[loans]]></category>

		<category><![CDATA[new york times]]></category>

		<category><![CDATA[Unithrive]]></category>

		<guid isPermaLink="false">http://blog.lrdesign.com/?p=63</guid>
		<description><![CDATA[One of my clients, UniThrive, was just written up in the New York Times.  Go check it out!   
An excerpt: 
In the photo, the young person’s eyes are brown and kind-looking. She is in need of financial help. A new Web site that brings together the charitable minded and those in need [...]]]></description>
			<content:encoded><![CDATA[<p>One of my clients, <a href="http://unithrive.org">UniThrive</a>, was just written up in the New York Times.  <a href="http://www.nytimes.com/2009/06/14/fashion/14unithrive.html?_r=1&#038;scp=1&#038;sq=unithrive&#038;st=cse">Go check it out</a>!   </p>
<p>An excerpt: </p>
<blockquote><p>In the photo, the young person’s eyes are brown and kind-looking. She is in need of financial help. A new Web site that brings together the charitable minded and those in need has posted the details of her request.</p>
<p>This is not one of those arrangements where donors can sponsor a needy child or a sorghum farmer in the developing world. The person asking for help is a 21-year-old neurobiology major at Harvard, and she is requesting a loan from Harvard alumni.</p></blockquote>
]]></content:encoded>
			<wfw:commentRss>http://blog.lrdesign.com/2009/06/new-york-times-article-about-unithrive/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Using link_to (or other helper methods) in a controller</title>
		<link>http://blog.lrdesign.com/2009/05/using-link_to-or-other-helper-methods-in-a-controller/</link>
		<comments>http://blog.lrdesign.com/2009/05/using-link_to-or-other-helper-methods-in-a-controller/#comments</comments>
		<pubDate>Wed, 06 May 2009 23:40:10 +0000</pubDate>
		<dc:creator>Evan</dc:creator>
		
		<category><![CDATA[Development]]></category>

		<category><![CDATA[Ruby on Rails]]></category>

		<category><![CDATA[controllers]]></category>

		<category><![CDATA[helper methods]]></category>

		<category><![CDATA[link_to]]></category>

		<guid isPermaLink="false">http://blog.lrdesign.com/?p=57</guid>
		<description><![CDATA[This one was a big aggravator to me lately.   I have one controller that needs to call link_to and url_for, which are normally helper methods you'd call from a view.   However, in this case during certain modifications to a record, I actually need to append user-visible HTML links to a block [...]]]></description>
			<content:encoded><![CDATA[<p>This one was a big aggravator to me lately.   I have one controller that needs to call link_to and url_for, which are normally helper methods you'd call from a view.   However, in this case during certain modifications to a record, I actually need to append user-visible HTML links to a block of HTML stored in that object, or possibly another one.</p>
<p>Specifically, I needed to put annotations in the description of a work order object that said, for example "this work order was escalated from <a href="/tasks/293">Problem Report 293</a>.   This was done in a create action that redirected at the end and never rendered a view, so I really did need to generate that link in the controller.   And for consistency with the rest of the application, I wanted to generate the link with link_to(@task).</p>
<p>Now, ActionView::Helpers::UrlHelper is not loaded in a Rails controller, even if you've put helper :all in application.rb (application_controller.rb in newer versions).   So, when I tried to use link_to in the controller, I got an error:</p>
<p><pre><code>NoMethodError: undefined method `link_to&#039; for #
/Users/evan/Development/Ruby/eclipticdb/app/helpers/tasks_helper.rb:64:in `task_link&#039;
/Users/evan/Development/Ruby/eclipticdb/app/controllers/tasks_controller.rb:103:in `escalate&#039;
... etc ...
</code></pre></p>
<h2>The first fix - but with a problem</h2>
<p>A year ago, I fixed this just by adding <code>include ActionView::Helpers::UrlHelper</code> at the top of that controller.  This worked great ... for a while.</p>
<p>Lately, I've been rewriting this application into a RESTful style - it had previously been a controller/action style application.  In the process, I started linking things with resource paths and polymorphic paths ... a lot of <code>link_to @task</code> and <code>edit_polymorphic_path(@task)</code> sorts of bits.   And these started breaking.   I began seeing this mysterious error:</p>
<h4>Error:</h4>
<p><pre><code>You have a nil object when you didn&#039;t expect it!
The error occurred while evaluating nil.url_for

... some code here that calls a link_to ...

Trace of template inclusion: /tasks/_task_panel.html.erb, /tasks/_task_tabbed_panel.html.erb, /tasks/index.html.erb

RAILS_ROOT: /Users/evan/Development/Ruby/eclipticdb
Application Trace | Framework Trace | Full Trace

vendor/rails/actionpack/lib/action_view/helpers/url_helper.rb:71:in `send&#039;
vendor/rails/actionpack/lib/action_view/helpers/url_helper.rb:71:in `url_for&#039;</code></pre></p>
<p>This one was a real bitch to debug, I have to say.   The line in question that was failing in url_helper.rb said this: <code>url = @controller.send(:url_for, options)</code>.   Clearly, @controller was nil ... which was very bizarre, because I never interact with that instance variable anywhere.</p>
<p>I thrashed around trying to find the cause of this error for quite some time.  Eventually I realized that the link_to method was only failing when called from a view in TasksController, and not from any other controller.  And then I realized that TasksController was the one where, a year ago, I'd put <code>include ActionView::Helpers::UrlHelper</code> at the top.   Somehow, including that helper in the controller was nullifying <code>@controller</code> when those helper method we called from within the view.   I removed the include and my polymorphic and resource links all started working again.</p>
<h2>Now back to the original problem!</h2>
<p>Of course, that then left me back with the problem I'd had a year ago ... needing to use link_to from within the controller and having no way to do it.   After a fair bit of googling around I found <a href="http://www.neeraj.name/blog/articles/740-using-helpers-in-controllers">this post</a> from Neeraj, which had an interesting approach -- but a commenter had suggested a much easier solution:</p>
<p>[sourcecode language='ror']self.class.helpers.link_to[/sourcecode]</p>
<p>I'm not certain where one would find this in the docs, but it does seem to have solved my problem for now.  Onward and upward!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lrdesign.com/2009/05/using-link_to-or-other-helper-methods-in-a-controller/feed/</wfw:commentRss>
		</item>
		<item>
		<title>New Project Launch: UniThive.org</title>
		<link>http://blog.lrdesign.com/2009/05/new-project-launch-unithiveorg/</link>
		<comments>http://blog.lrdesign.com/2009/05/new-project-launch-unithiveorg/#comments</comments>
		<pubDate>Tue, 05 May 2009 18:18:00 +0000</pubDate>
		<dc:creator>Evan</dc:creator>
		
		<category><![CDATA[Projects]]></category>

		<guid isPermaLink="false">http://blog.lrdesign.com/?p=56</guid>
		<description><![CDATA[Where have I been the last few months?
 Busy building and launching UniThrive.org!
UniThrive.org is a fantastic new non-profit startup that seeks to help reduce the cost of higher education by networking college students with alumni, and facilitating direct, zero-interest loans between alumni and students to defray tuition costs.   
Technologically, UniThrive is a Rails [...]]]></description>
			<content:encoded><![CDATA[<h2>Where have I been the last few months?</h2>
<h3> Busy building and launching <a href="http://unithrive.org">UniThrive.org</a>!</h3>
<p><a href='http://blog.lrdesign.com/wp-content/uploads/2009/05/unithrive_logo.jpg'><img src="http://blog.lrdesign.com/wp-content/uploads/2009/05/unithrive_logo.jpg" alt="UniThrive Logo" title="unithrive_logo" width="240" height="117" class="alignleft size-full wp-image-55" /></a>UniThrive.org is a fantastic new non-profit startup that seeks to help reduce the cost of higher education by networking college students with alumni, and facilitating direct, zero-interest loans between alumni and students to defray tuition costs.   </p>
<p>Technologically, UniThrive is a Rails application that began as a fork of the open-source social networking application <a href="http://insoshi.org">Insoshi</a>.  Since forking  Insoshi, we've nearly doubled the size of the code.</p>
<p>Today, UniThrive is in a live beta test available to students and alumni of Harvard University.   Take a look, and check out the <a href="http://unithrive.org/blog">UniThrive Blog</a>!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lrdesign.com/2009/05/new-project-launch-unithiveorg/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Single Table Inheritance and RESTful Routes</title>
		<link>http://blog.lrdesign.com/2009/03/single-table-inheritance-and-restful-routes/</link>
		<comments>http://blog.lrdesign.com/2009/03/single-table-inheritance-and-restful-routes/#comments</comments>
		<pubDate>Tue, 17 Mar 2009 21:00:39 +0000</pubDate>
		<dc:creator>Evan</dc:creator>
		
		<category><![CDATA[Development]]></category>

		<category><![CDATA[Ruby on Rails]]></category>

		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[REST]]></category>

		<category><![CDATA[RESTful]]></category>

		<category><![CDATA[routes]]></category>

		<category><![CDATA[single table inheritance]]></category>

		<category><![CDATA[STI]]></category>

		<guid isPermaLink="false">http://blog.lrdesign.com/?p=52</guid>
		<description><![CDATA[I'm converting an old, controller/action/id style Rails application to a more RESTful way of doing things, and ran into a brief roadblock:   one of my main tables uses single table inheritance to generate three subclasses of items.   I never actually use the superclass "task", I only use the three subclasses "action [...]]]></description>
			<content:encoded><![CDATA[<p>I'm converting an old, controller/action/id style Rails application to a more RESTful way of doing things, and ran into a brief roadblock:   one of my main tables uses single table inheritance to generate three subclasses of items.   I never actually use the superclass "task", I only use the three subclasses "action item", "work order", and "problem report".</p>
<p>So, I ran into this little challenge:  all three STI subclasses use the same controller, "tasks", because they all have essentially the same behavior and differ only in minor details.    But, when I do a resources map:</p>
<p><code>map.resources :tasks</code></p>
<p>Then I get errors in much of my code when I say things like <code>redirect_to @task</code>, because if that task happens to be an ActionItem, it's trying to call <code>action_item_path(@task)</code>, which doesn't exist.</p>
<p>I googled around a bit to no result.  Striking out on my own, it turns out the answer is as simple as mapping each resource independently, and just overriding the controller in map.resources:</p>
<h4>In config/routes.rb</h4>
<p><pre><code>map.resources :tasks
map.resources :action_items, :controller =&gt; &#039;tasks&#039;
map.resources :work_orders, :controller =&gt; &#039;tasks&#039;
map.resources :problem_reports, :controller =&gt; &#039;tasks&#039;
</code></pre></p>
<p>Now, <code>redirect_to @task</code> works just fine regardless of which subclass <code>@task</code> happens to be.   </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lrdesign.com/2009/03/single-table-inheritance-and-restful-routes/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Bypassing mass assignment for update_attributes</title>
		<link>http://blog.lrdesign.com/2009/03/bypassing-mass-assignment-for-update_attributes/</link>
		<comments>http://blog.lrdesign.com/2009/03/bypassing-mass-assignment-for-update_attributes/#comments</comments>
		<pubDate>Sat, 14 Mar 2009 21:45:05 +0000</pubDate>
		<dc:creator>Evan</dc:creator>
		
		<category><![CDATA[Development]]></category>

		<category><![CDATA[Ruby on Rails]]></category>

		<category><![CDATA[Web Security]]></category>

		<category><![CDATA[Active Record]]></category>

		<category><![CDATA[mass assignment]]></category>

		<category><![CDATA[security]]></category>

		<category><![CDATA[update_attributes]]></category>

		<guid isPermaLink="false">http://blog.lrdesign.com/?p=51</guid>
		<description><![CDATA[I've been following this excellent post by M. Hartl and this post by E. Chapweske banishing mass assignment from one of my Rails applications due to launch soon.
I'm following Chapweske's approach of blocking mass assignment by default in all models, by putting this line in an initializer:
ActiveRecord::Base.send(:attr_accessible, nil)
This had the expected side effect of breaking [...]]]></description>
			<content:encoded><![CDATA[<p>I've been following <a href="http://blog.insoshi.com/2008/09/21/finding-and-fixing-mass-assignment-problems-in-rails-applications/#">this excellent post by M. Hartl</a> and <a href="http://railspikes.com/2008/9/22/is-your-rails-application-safe-from-mass-assignment">this post by E. Chapweske</a> banishing mass assignment from one of my Rails applications due to launch soon.</p>
<p>I'm following Chapweske's approach of blocking mass assignment by default in all models, by putting this line in an initializer:</p>
<p><code>ActiveRecord::Base.send(:attr_accessible, nil)</code></p>
<p>This had the expected side effect of breaking several zillion tests, because tests frequently use things like Model.build() and Model.create!() to generate on-demand fixtures during testing.  Hartl has a great bit of code that creates unsafe_build() and unsafe_create() methods in ActiveRecord.   You can use these methods instead of build() and create() to function as expected in your tests.</p>
<p>This works great, except that I also use the mass-assignment method update_attributes! in my tests and specs frequently, particularly when I want to spec the effect a change on one model has on an associated models' methods.   So, I expanded on Hartl's helper code a bit, to give myself the necessary methods.   In case it helps anyone else:</p>
<h4>/lib/initializers/unsafe_build_and_create.rb</h4>
<p><pre><code>class ActiveRecord::Base

&nbsp;&nbsp;# Build and create records unsafely, bypassing attr_accessible.
&nbsp;&nbsp;# These methods are especially useful in tests and in the console.

&nbsp;&nbsp;def self.unsafe_build(attrs)
&nbsp;&nbsp;&nbsp;&nbsp;record = new
&nbsp;&nbsp;&nbsp;&nbsp;record.unsafe_attributes = attrs
&nbsp;&nbsp;&nbsp;&nbsp;record
&nbsp;&nbsp;end

&nbsp;&nbsp;def self.unsafe_create(attrs)
&nbsp;&nbsp;&nbsp;&nbsp;record = unsafe_build(attrs)
&nbsp;&nbsp;&nbsp;&nbsp;record.save
&nbsp;&nbsp;&nbsp;&nbsp;record
&nbsp;&nbsp;end

&nbsp;&nbsp;def self.unsafe_create!(attrs)
&nbsp;&nbsp;&nbsp;&nbsp;unsafe_build(attrs).save!
&nbsp;&nbsp;end
&nbsp;&nbsp;
&nbsp;&nbsp;def unsafe_update_attributes!(attrs)
&nbsp;&nbsp;&nbsp;&nbsp;self.unsafe_attributes = attrs
&nbsp;&nbsp;&nbsp;&nbsp;self.save!
&nbsp;&nbsp;end

&nbsp;&nbsp;def unsafe_update_attributes(attrs)
&nbsp;&nbsp;&nbsp;&nbsp;self.unsafe_attributes = attrs
&nbsp;&nbsp;&nbsp;&nbsp;self.save
&nbsp;&nbsp;end

&nbsp;&nbsp;def unsafe_attributes=(attrs)
&nbsp;&nbsp;&nbsp;&nbsp;attrs.each do |k, v|
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;send(&quot;#{k}=&quot;, v)
&nbsp;&nbsp;&nbsp;&nbsp;end
&nbsp;&nbsp;end
end</code></pre></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lrdesign.com/2009/03/bypassing-mass-assignment-for-update_attributes/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Don’t overwrite Rails’ built-in instance variables</title>
		<link>http://blog.lrdesign.com/2009/02/dont-overwrite-rails-built-in-instance-variables/</link>
		<comments>http://blog.lrdesign.com/2009/02/dont-overwrite-rails-built-in-instance-variables/#comments</comments>
		<pubDate>Sat, 14 Feb 2009 02:40:36 +0000</pubDate>
		<dc:creator>Evan</dc:creator>
		
		<category><![CDATA[Development]]></category>

		<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://blog.lrdesign.com/?p=46</guid>
		<description><![CDATA[So I'm hammering away at a project tonight, writing a few specifications for a module.  I've changed very little - or so I think - when five of my specifications start reporting this error:
NoMethodError in &#039;LoansController POST &#039;create&#039; with valid parameters should succeed&#039;
undefined method `env&#039; for &#60;LoanRequest:0x3729e00&#62;
This happens on the line where I call post [...]]]></description>
			<content:encoded><![CDATA[<p>So I'm hammering away at a project tonight, writing a few specifications for a module.  I've changed very little - or so I think - when five of my specifications start reporting this error:</p>
<p><pre><code>NoMethodError in &#039;LoansController POST &#039;create&#039; with valid parameters should succeed&#039;
undefined method `env&#039; for &lt;LoanRequest:0x3729e00&gt;</code></pre></p>
<p>This happens on the line where I call <code>post :create</code> in a controller spec.   Undefined method 'env'?   What's that about?  I'm certainly not trying to call a method named "env".</p>
<p>It took me a little bit to figure out what was going on.  See, this series of tests needed access to a particular LoanRequest object I was pulling out of fixtures.   So I'd put above the tests:</p>
<p><pre><code>before(:each) do
&nbsp;&nbsp;... some other stuff ...
&nbsp;&nbsp;@request = loan_requests(:johns_loan_request)&nbsp;&nbsp;# fetch fixture
end</code></pre></p>
<p>Well, kids, it just so turns out that it's a bad idea to overwrite the <code>@request</code> instance variable in any rails context.   Who knew?</p>
<p>Come to think of it, it would be nice to change the accessibility and/or mutability of Rails' basic instance variables and classes to prevent this kind of accidental overwrite by the programmer.  Because when you make that mistake, it's invariably a bit of a pain to figure out because the error it causes is obscure.</p>
<p>Maybe I'll have to dig into the code one of these days to see if anything can be done about it. </p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lrdesign.com/2009/02/dont-overwrite-rails-built-in-instance-variables/feed/</wfw:commentRss>
		</item>
		<item>
		<title>In Defense of Sass</title>
		<link>http://blog.lrdesign.com/2009/02/in-defense-of-sass/</link>
		<comments>http://blog.lrdesign.com/2009/02/in-defense-of-sass/#comments</comments>
		<pubDate>Wed, 11 Feb 2009 23:59:48 +0000</pubDate>
		<dc:creator>Evan</dc:creator>
		
		<category><![CDATA[Development]]></category>

		<category><![CDATA[HTML, CSS, and Web Standards]]></category>

		<category><![CDATA[CSS]]></category>

		<category><![CDATA[sass]]></category>

		<guid isPermaLink="false">http://blog.lrdesign.com/?p=45</guid>
		<description><![CDATA[I've been playing with Sass and Haml in my rails projects the last few months.   While I'm a bit ambivalent about Haml, I've wholeheartedly adopted Sass.  A friend just forwarded me this post at fecklessmind, which excoriates Sass as a maintainability nightmare.
While I understand the guy's complaints, I have to say I [...]]]></description>
			<content:encoded><![CDATA[<p>I've been playing with <a href="http://Haml.hamptoncatlin.com/docs/rdoc/classes/Sass.html">Sass</a> and <a href="http://Haml.hamptoncatlin.com/">Haml</a> in my rails projects the last few months.   While I'm a bit ambivalent about Haml, I've wholeheartedly adopted Sass.  A friend just forwarded me <a href="http://fecklessmind.com/2009/01/28/fuck-Sass/">this post at fecklessmind</a>, which excoriates Sass as a maintainability nightmare.</p>
<p>While I understand the guy's complaints, I have to say I disagree.  I think he's complaining about a code convention that he shouldn't be following in the first place, rather than the underlying language, and he's ignoring some of the other most useful things Sass brings to the table.</p>
<h3>Nesting in Sass</h3>
<p>One of the most common problems I've faced over the last eight years of writing stylesheets is interfering selectors.   When you have a complex cascading selector, it's often not obvious exactly where it will apply, because of the way priorities work.   So a hundred times I've set some styling on UL's and LI's (thinking of ones in my #content block), only to have them accidentally interfere with the layout of my <a href="http://www.alistapart.com/articles/dropdowns">suckerfish dropdowns</a> back in #nav.  </p>
<p>That's an easy case, but sometimes with complex selectors it can be hard to figure out who's interfering with whom.   However, once you've found the culprit, the solution is generally to go back and wrap all of the rules in an outer selector,  changing all of my <code>li {rule}</code> selectors to <code>#nav li</code> selectors, or whatever.   When you have twenty different rules in that section, doing this is a royal pain in the butt.   Especially when you have multiple tag selectors on one line: it's seriously annoying to change the nice clean  <code>h1, h2, h3</code> to <code>#content h1, #content h2, #content h3!</code></p>
<p>When you do need these wraps, Sass makes it super easy via auto-nesting:</p>
<p><pre><code>#nav
&nbsp;&nbsp;li
&nbsp;&nbsp;&nbsp;&nbsp;:color #whatever
&nbsp;&nbsp;&nbsp;&nbsp;:float left

&nbsp;&nbsp;a
&nbsp;&nbsp;&nbsp;&nbsp;:whatever etc
</code></pre></p>
<p>will compile to:<br />
<pre><code>#nav li {
&nbsp;&nbsp;&nbsp;&nbsp;color: #whatever
&nbsp;&nbsp;&nbsp;&nbsp;float: left
}
#nav a {
&nbsp;&nbsp;&nbsp;&nbsp;whatever: etc
}
</code></pre></p>
<p>Now, the author of fecklessmind is complaining about how this makes rules harder to find, and how it slows down parsing.   Both of these can be true, if you overdo it.  But I don't - Sass doesn't force you to wrap your rules this way, and I frequently don't when it doesn't provide any benefit or when it would cause me to write redundant rules.  I can and frequently do write single-line cascading selectors, and rules without wraps at all - the very things fecklessmind is complaining that Sass takes away from him.  </p>
<p>Nothing about Sass prevents me from writing things like this:<br />
<pre><code>body #nav ul li a
&nbsp;&nbsp;:float left
</code></pre></p>
<p>or even<br />
<pre><code>#content h1, #nav h2, .article h3, p h4
&nbsp;&nbsp;:font-weight bold
</code></pre> </p>
<p>If that's really what I want to do.  I learned how and when to wrap selectors with a near-decade  of writing CSS, and I apply those same guidelines when I write Sass - Sass just makes it easier when I do want to do it.</p>
<h3>The benefits of nesting early</h3>
<p>While I don't use Sass nesting everywhere I possibly could, I do often use it slightly more than would be absolutely required.  </p>
<p>The reason is that it heads off a lot of annoying bugs with interfering selectors.  For example, say a rule  I wrote for .article .body p, and it's not getting applied.  After some sleuthwork (long, painful, frustrating sleuthwork if I'm on a platform without firebug, like IE), it turns out this is because there's a #content p rule 2000 lines earlier in the CSS file that's obscuring it.   When I nest things in Sass to create a clean cascade hierarchy, this kind of interference is far less likely to occur in the first place.</p>
<h2>Meanwhile, the other benefits of Sass</h2>
<p>CSS is riddled with problems, and Sass solves two of the most egregious:  magic numbers/constants, and compiled server-side imports.</p>
<h3>Eliminating magic numbers in CSS</h3>
<p>For constants, Sass lets me define commonly used tokens (like colors, for example), and reuse them throughout my stylesheets.  This means if I want to adjust a color, I can change it in only one place and the result is reflected throughout my code.  Very handy:<br />
<pre><code>
!main_link_color = #48950a

a 
&nbsp;&nbsp;:color= !main_link_color

#content h1
&nbsp;&nbsp;:border-width 0 0 1px 0
&nbsp;&nbsp;:border-color= !main_link_color
</code></pre></p>
<p>Now, if the client says "make the links blue, not green", I can change that constant and it gets automatically reflected everywhere else.   Brilliant.</p>
<h3>Organizing my code</h3>
<p>fecklessmind says this:</p>
<blockquote><p>... imagine that the stylesheet is 5000-lines long and you’re looking for p selector, rather than #article. In classic CSS you could just search for #main p, but in Sass they are miles apart. Swell, isn’t it?
</p></blockquote>
<p><strong>A five-thousand-line line file?</strong>   <em>You're doing it wrong.</em>   No code should <em>ever</em> look like that. CSS is the only major language that compels you to work that way and Sass fixes it.</p>
<p>Every good programming language lets me put my code across multiple files, in a nice, organized heirarchy.   One class per file and all that: essential for readability and maintainability.   But if I use CSS, I can't very well organize my stylesheets into multiple files.   If I do, I have to import them client-side, which generates extra hits for the user's browser and extra load for my server.  As a result, CSS files tend to be monolithic multiple-kiloline monstrosities. </p>
<p>Sass fixes this.  If I use @import to import a Sass file into another Sass file, Sass automatically and transparently compiles that server-side and ships out a single file to the user. </p>
<p>The result is that, writing Sass, I often have 20-30 files containing only a page or so of code, each for a specific feature or layout section.   The client still only sees screen.css (and maybe print.css, mobile.css, and ie6.css), but screen.css contains the compiled contents of layout.sass, nav.sass, links.sass, content.sass, footer.sass, etc.   In case I need to scan through the compiled screen.css and figure out where a rule came from, I start each file with a single comment containing the name of the file;  <code>/*------</code> nav.sass and such.  </p>
<p>If the rule is for paragraphs that could appear anywhere in #main, in my Sass code it would be a file called main.sass, which is usually a relatively short file; 50-60 lines.   (All the things destined for other elements would appear in articles.sass, or calendar.sass, or data_tables.sass, keeping main.sass short for only the universal elements).</p>
<p>That logical grouping &#8212; the way every other programming language does it  &#8212; helps me find my CSS rules much more quickly, I think, than fecklessmind's "search for one-line selectors" would.   Because with his approach, I might <em>think</em> I'm searching for <code>#main p</code>, when in fact what I really want is <code>#main .section p</code>, and thus my search won't find it.</p>
<p>In reality, there's no way to make a single 5000-line file easily maintainable, period.   fecklessmind's little tricks are just that: tricks built from years of experience working in a broken system.  Better to use logical organization to solve the problem, and Sass lets me do this.  </p>
<p>The bottom line is, badly-written Sass could be horrible to maintain, and maybe worse in some ways than badly-written CSS (but better in others, particularly in weird cross-reactions between unwrapped css selectors).   But the same is true of badly-written code of any type.  And in my experience Sass gives me much better tools to write maintainable stylesheets than CSS alone does.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lrdesign.com/2009/02/in-defense-of-sass/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Fixing problems with sphinx search</title>
		<link>http://blog.lrdesign.com/2008/07/fixing-problems-with-sphinx-search/</link>
		<comments>http://blog.lrdesign.com/2008/07/fixing-problems-with-sphinx-search/#comments</comments>
		<pubDate>Thu, 24 Jul 2008 17:44:02 +0000</pubDate>
		<dc:creator>Evan</dc:creator>
		
		<category><![CDATA[Development]]></category>

		<category><![CDATA[Ruby on Rails]]></category>

		<category><![CDATA[daemon]]></category>

		<category><![CDATA[foxy fixtures]]></category>

		<category><![CDATA[Insoshi]]></category>

		<category><![CDATA[sphinx]]></category>

		<category><![CDATA[Ultrasphinx]]></category>

		<guid isPermaLink="false">http://blog.lrdesign.com/?p=42</guid>
		<description><![CDATA[I've been working a lot this week with sphinx and ultrasphinx on a project that's a fork of Insoshi.    Insoshi is in the process of switching search from ferret to sphinx, and sphinx has been integrated into the Insoshi edge branch.
I've had dozens of problems, in fact it's fair to say I've spent upwards of [...]]]></description>
			<content:encoded><![CDATA[<p>I've been working a lot this week with <a href="http://www.sphinxsearch.com/">sphinx</a> and <a href="http://agilewebdevelopment.com/plugins/ultrasphinx">ultrasphinx</a> on a project that's a fork of <a href="http://insoshi.com">Insoshi</a>.    Insoshi is in the process of switching search from ferret to sphinx, and sphinx has been integrated into the Insoshi edge branch.</p>
<p>I've had dozens of problems, in fact it's fair to say I've spent upwards of 15 hours just debugging ultrasphinx and getting my tests to pass.   There were several problems; here are the main three and how I fixed each one.</p>
<p>This should be useful to anyone upgrading Insoshi to the sphinx version, or to anyone else trying to get ultrasphinx working in their Rails project.   I definitely don't recommend starting with this post if you're just starting out with sphinx.  Instead, go read this much better <a href="http://blog.insoshi.com/2008/07/17/searching-a-ruby-on-rails-application-with-sphinx-and-ultrasphinx/">introductory tutorial</a> from the guys over at Insoshi.  Then if you have problems, come back here and you may find solutions.</p>
<h2>Getting search tests (or specs) to pass with sphinx</h2>
<p>This one is pretty simple, in retrospect, but it can be frustrating and opaque if you are used to ferret.  Unlike ferret, sphinx (at least via ultrasphinx) runs only via a daemon.   Where acts_as_ferret uses a daemon only for the production environment and just accesses the index files directly in test or development, ultrasphinx can only get to the indexes through the daemon.</p>
<p>So, to run your tests, you just build up the indexes for test and run them.  In this case, I'm running the specs for Insoshi's searches controller:</p>
<h4>From the command line in $RAILS_ROOT:</h4>
<p><pre><code>rake db:test:prepare
rake ultrasphinx:configure RAILS_ENV=test
rake ultrasphinx:index RAILS_ENV=test
rake ultrasphinx:daemon:start RAILS_ENV=test
script/spec spec/controllers/searches_controller_spec.rb</code></pre></p>
<p>The problem, of course, is that it doesn't work!   The reason is that db:test:prepare creates the <em>structure</em> of your database, but doesn't load any of your fixtures as data: the test db is empty..  So when you run the index command, an empty index is built.   You can see this from the output of that first index command, which will look something like this:</p>
<p><pre><code>collected 0 docs, 0.0 MB
total 0 docs, 0 bytes
total 0.078 sec, 0.00 bytes/sec, 0.00 docs/sec</code></pre></p>
<p>Ultrasphinx has built an empty index.</p>
<h3>The solution</h3>
<p>The solution, believe it or not, is to run the tests, let them fail, re-index, and run the tests again (Many thanks to Long Nguyen at Insoshi for helping me figure this one out):</p>
<p><pre><code>rake db:test:prepare
rake ultrasphinx:configure RAILS_ENV=test
rake ultrasphinx:index RAILS_ENV=test
rake ultrasphinx:daemon:start RAILS_ENV=test
script/spec spec/controllers/searches_controller_spec.rb&nbsp;&nbsp; #FAIL!!
rake ultrasphinx:index RAILS_ENV=test
script/spec spec/controllers/searches_controller_spec.rb&nbsp;&nbsp; #PASS!!
</code></pre></p>
<p>The first attempt to run the specs loads the fixtures, and leaves them in the database, thus letting the subsequent index command build an actual index.</p>
<h2>Running sphinx for both test and development environments at the same time</h2>
<p>The next big challenge was enabling behavior-driven development.  I like to work with autotest and growl running constantly in the background.   But this was tough to do with sphinx, because the daemon needed to be stopped and re-started, and the index re-created for each environment, alternately running all of the above commands either with or without RAILS_ENV=test.  </p>
<p>The solution is to set up your ultrasphinx base configuration to completely separate both the test and development indexes and to let the daemons for the two environments listen on different ports.  I had tried something like this and come close, but not quite, when Long at Insoshi again bailed me out.   You need to change the port (in two places), and the paths of the logs, pidfile, and index directories so that test and development daemons are using entirely separate resources.   Here's a diff of my test.conf and default.conf:</p>
<p><pre><code>33c33
&lt;&nbsp;&nbsp; port = 3312
---
&gt;&nbsp;&nbsp; port = 3322
35c35
&lt;&nbsp;&nbsp; log = log/searchd.log
---
&gt;&nbsp;&nbsp; log = log/searchd_test.log
39c39
&lt;&nbsp;&nbsp; pid_file = log/searchd.pid
---
&gt;&nbsp;&nbsp; pid_file = log/searchd_test.pid
50c50
&lt;&nbsp;&nbsp; server_port = 3312
---
&gt;&nbsp;&nbsp; server_port = 3322
57c57
&lt;&nbsp;&nbsp; sql_range_step = 5000&nbsp;&nbsp; 
---
&gt;&nbsp;&nbsp; sql_range_step = 999999999&nbsp;&nbsp; 
64c64
&lt;&nbsp;&nbsp; path = sphinx
---
&gt;&nbsp;&nbsp; path = sphinx_test</code></pre></p>
<p>The <code>sql_range_step</code> is related to the next issue, which is that sphinx does not play well with foxy fixtures.   Anyway, make the above changes and you should be able to run test and development sphinx daemons at the same time:</p>
<p><pre><code>rake db:test:prepare
rake ultrasphinx:configure
rake ultrasphinx:configure RAILS_ENV=test
rake ultrasphinx:index
rake ultrasphinx:index RAILS_ENV=test
rake ultrasphinx:daemon:start
rake ultrasphinx:daemon:start RAILS_ENV=test
</code></pre></p>
<p>If it worked, you should see separate indexes in $RAILS_ROOT/sphinx and $RAILS_ROOT/sphinx_test, and two daemons running, which you can confirm with <code>ps waux | grep searchd</code>:<br />
<pre><code>evan&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1339&nbsp;&nbsp; 0.0&nbsp;&nbsp;0.0&nbsp;&nbsp;&nbsp;&nbsp;78100&nbsp;&nbsp;&nbsp;&nbsp;292 s000&nbsp;&nbsp;S&nbsp;&nbsp;&nbsp;&nbsp; 5:37PM&nbsp;&nbsp; 0:00.52 searchd --config &lt;YOUR_RAILS_ROOT&gt;/config/ultrasphinx/test.conf
evan&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1326&nbsp;&nbsp; 0.0&nbsp;&nbsp;0.0&nbsp;&nbsp;&nbsp;&nbsp;78100&nbsp;&nbsp;&nbsp;&nbsp;292 s000&nbsp;&nbsp;S&nbsp;&nbsp;&nbsp;&nbsp; 5:36PM&nbsp;&nbsp; 0:00.68 searchd --config &lt;YOUR_RAILS_ROOT&gt;/config/ultrasphinx/development.conf</code></pre></p>
<h2>Getting sphinx to play well with foxy fixtures</h2>
<p>The next problem I discovered was that on some machines, but not others, running my search specs would result in these weird errors:<br />
<pre><code>1)
ActiveRecord::RecordNotFound in &#039;SearchesController Person searches should search by name&#039;
Couldn&#039;t find Person with ID=328556765
/var/www/domains/unithrive/vendor/plugins/ultrasphinx/lib/ultrasphinx/search/internals.rb:308:in `reify_results&#039;
/var/www/domains/unithrive/vendor/plugins/ultrasphinx/lib/ultrasphinx/search/internals.rb:286:in `each&#039;
/var/www/domains/unithrive/vendor/plugins/ultrasphinx/lib/ultrasphinx/search/internals.rb:286:in `reify_results&#039;
/var/www/domains/unithrive/vendor/plugins/ultrasphinx/lib/ultrasphinx/search.rb:362:in `run&#039;
/var/www/domains/unithrive/vendor/plugins/ultrasphinx/lib/ultrasphinx/search/internals.rb:352:in `perform_action_with_retries&#039;
/var/www/domains/unithrive/vendor/plugins/ultrasphinx/lib/ultrasphinx/search.rb:342:in `run&#039;
/var/www/domains/unithrive/app/controllers/searches_controller.rb:38:in `index&#039;
./spec/controllers/searches_controller_spec.rb:51:
script/spec:4:</code></pre></p>
<p>When I poked into this "Couldn't find Person with ID=328556765" error, it seemed like sphinx was <em>almost</em> working.  The index was set up, and the search was finding someone in the index during the test.  Ultrasphinx was passing back the id 328556765, which didn't exist in the database.  So why would Sphinx "find" a record in its index but then pass back an ID for a database record that didn't exist?</p>
<p>And furthermore, why would it work on one machine, but not on another?</p>
<p>The brainstorm came when I checked what the actual database IDs were for this particular record, with Person.find_by_name("fixtures' name").id.  On machines where it worked, the id was a huge number (is it generally is with foxy fixtures), but on machines where it didn't work, the id was an <em>even huger</em> number. </p>
<p>Sphinx tries to make sure that all items that get indexed have a different index in sphinx, and it does this by multiplying all of your id's by N, where N is the number of models getting indexed, and adding an offset of 0 for the first model, 1 for the second, etc.   This guarantees that every record from every table will have a unique id.  In the case of this application, all of my Person records were getting indexed by sphinx as (Person#id * 4 + 2).   </p>
<h3>Danger, Will Robinson:  32-bit int rollover!</h3>
<p>The problem is that foxy fixtures generate their own ids from a hash of the fixture label, and those ids can be anywhere in the 32-bit unsigned integer space.  But Sphinx also stores ids as 32-bit unsigned integers.   This means if you happen to get a large fixture id, and then sphinx multiplies it by 4 (or whatever; it could be higher if you have more indexed models), your id will rollover and come out as (id * N + n) % (2^32).   Sphinx will store that result, and then when it finds the record in a search, it will try to recreate the original id by subtracting n and dividing by N ... giving you the wrong id.  Your test will fail to find the record.</p>
<p>Incidentally, this problem with foxy fixtures is why your test.base file needs the line <code>sql_range_step = 999999999</code>.  Sphinx builds indexes by searching a few ids at a time.  But the ids generated by foxy fixtures are so big that if sphinx only collects them in ranges of 5000 at a time, it will take forever to find them all.</p>
<p>After some googling, I found that these issues are discussed in a <a href="http://rubyforge.org/forum/message.php?msg_id=43937">thread over at RubyForge</a>. </p>
<h3>The solution</h3>
<p>I'm working on a plugin that monkeypatches foxy fixtures to create sequential, low-numbered IDs.  In the meantime, you can just compile sphinx to support 64-bit ids, which should give you plenty of headroom to handle foxy fixture ids multiplied by N in sphinx<sup>*</sup>:</p>
<h4>In your sphinx source directory:</h4>
<p><pre><code>configure --enable-id64
make
sudo make install</code></pre></p>
<p>That should do it.  Let me know in comments if any of this information helped you.</p>
<p><sup>*</sup>At least until you start approaching 2^32 models in your application, that is.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lrdesign.com/2008/07/fixing-problems-with-sphinx-search/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Changing the origin of your git repository</title>
		<link>http://blog.lrdesign.com/2008/07/changing-the-origin-of-your-git-repository/</link>
		<comments>http://blog.lrdesign.com/2008/07/changing-the-origin-of-your-git-repository/#comments</comments>
		<pubDate>Wed, 16 Jul 2008 21:02:38 +0000</pubDate>
		<dc:creator>Evan</dc:creator>
		
		<category><![CDATA[Development]]></category>

		<category><![CDATA[Git]]></category>

		<category><![CDATA[GitHub]]></category>

		<category><![CDATA[origin]]></category>

		<category><![CDATA[repository]]></category>

		<guid isPermaLink="false">http://blog.lrdesign.com/?p=41</guid>
		<description><![CDATA[This is pretty basic and there's plenty of documentation on the web, but this morning I found it difficult to locate with a google search.  Maybe I just didn't know the right terms.  (searching "git repository change origin" seems obvious to me, but the results were useless.)  Hopefully this post will help [...]]]></description>
			<content:encoded><![CDATA[<p>This is pretty basic and there's plenty of documentation on the web, but this morning I found it difficult to locate with a google search.  Maybe I just didn't know the right terms.  (searching "git repository change origin" seems obvious to me, but the results were useless.)  Hopefully this post will help people find the documentation they are looking for if they are searching the same way I was.</p>
<p>Anyway, suppose you have a local git repository that you cloned from some remote repository at, say <code>git://user@dev.foo.com/git/repos/path</code>, and you've been happily <code>pull</code>ing, <code>push</code>ing and <code>rebase</code>ing to and from that remote repository.  But now you or your team leader have moved that remote repository to a new location, and you'd like to point your repository to the new URL without having to do a full checkout.   </p>
<p>What you need to do is change your 'origin' setting.   Unfortunately, there's no trivially easy way to do this from the command line in current versions of git.   Instead, you edit <code>.git/config</code> in your project root, which may look something like this:</p>
<p><pre><code>...
[remote &quot;origin&quot;]
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;url = git://user@dev.foo.com/git/repos/path
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;fetch = +refs/heads/*:refs/remotes/origin/*
...</code></pre></p>
<p>or if your 'remote' is actually local:</p>
<p><pre><code>...
[remote &quot;origin&quot;]
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;url = /path/to/repos/on/this/machine
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;fetch = +refs/heads/*:refs/remotes/origin/*
...</code></pre></p>
<p>All you need to do is edit that file with your favorite editor and change the <code>url =</code> setting to your new location.   Assuming the new repository is correctly set up and you have your URL right, you'll be happily pushing and pulling to and from your new remote location.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lrdesign.com/2008/07/changing-the-origin-of-your-git-repository/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
