<?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:slash="http://purl.org/rss/1.0/modules/slash/" 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>
	<lastBuildDate>Fri, 16 Oct 2009 20:20:19 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</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><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com" /><item>
		<title>Back up after hacking incident</title>
		<link>http://blog.lrdesign.com/2009/10/back-up-after-hacking-incident/</link>
		<comments>http://blog.lrdesign.com/2009/10/back-up-after-hacking-incident/#comments</comments>
		<pubDate>Fri, 16 Oct 2009 20:20:19 +0000</pubDate>
		<dc:creator>Evan</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.lrdesign.com/?p=79</guid>
		<description><![CDATA[This blog, along with a dozen or so other CMS-driven sites I maintain, was compromised by a hacker recently.   I've finally gotten this one back up and am working on the others.
]]></description>
			<content:encoded><![CDATA[<p>This blog, along with a dozen or so other CMS-driven sites I maintain, was compromised by a hacker recently.   I've finally gotten this one back up and am working on the others.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lrdesign.com/2009/10/back-up-after-hacking-incident/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>When ‘rake spec’ and ’spec spec’ produce different results</title>
		<link>http://blog.lrdesign.com/2009/08/when-rake-spec-and-spec-spec-produce-different-results/</link>
		<comments>http://blog.lrdesign.com/2009/08/when-rake-spec-and-spec-spec-produce-different-results/#comments</comments>
		<pubDate>Sun, 09 Aug 2009 18:31:49 +0000</pubDate>
		<dc:creator>Evan</dc:creator>
				<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://blog.lrdesign.com/?p=74</guid>
		<description><![CDATA[AKA adventures in class loading.
A couple of days ago I did some significant work in authorization in one of my apps, involving creating a Groups class with an HABTM relationship to Person, so I could assign roles to people a group at a time.  It all worked out great, and I pushed the product [...]]]></description>
			<content:encoded><![CDATA[<p>AKA adventures in class loading.</p>
<p>A couple of days ago I did some significant work in authorization in one of my apps, involving creating a Groups class with an HABTM relationship to Person, so I could assign roles to people a group at a time.  It all worked out great, and I pushed the product to GitHub.  The next day, my collaborator wrote in that my recent contribution broke 119 specs.</p>
<p>I pulled and retested the code, and everything worked perfectly.  WTF?   After a bit of investigation, I discovered that the specs worked great when I ran 'autotest' or 'spec spec', but that 119 specs broke when I ran the exact same spec suite with 'rake spec'!  Double WTF.</p>
<h3>Setting constants at class loading</h3>
<p>Ultimately, I tracked the problem down to this line and method, in Person.rb:<br />
<code>class Person << ActiveRecord::Base<br />
  ADMIN_GROUP = Group.find_by_name('Admin')<br />
  def admin?<br />
    groups.include? ADMIN_GROUP<br />
  end<br />
end<br />
</code></p>
<p>I consider a person an administrator if they are a member of this group, and I was loading it as a constant at the class level in order to avoid having to query the database again every time Person#admin? is called.   This worked just fine for me, both in the application, and every time I ran Person#admin?.</p>
<p>But, remarkably, ADMIN_GROUP does not get initialized correctly when I run the tests via rake.   I found this via the ruby debugger, running in this particular spec in spec/models/person_spec.rb:</p>
<p><code><br />
describe Person do<br />
  it "should load an admin user from fixture" do<br />
    debugger<br />
    people(:admin).should be_admin<br />
  end<br />
end<br />
</code></p>
<p>When I run the specs and evaluate Person::ADMIN_USER, I get very different results depending on which spec runner I'm using:</p>
<h3>Running 'spec spec/models/person_spec.rb':</h3>
<p><code><br />
[11:17:54 CITAlumni]$ spec spec/models/person_spec.rb<br />
spec/models/person_spec.rb:64<br />
people(:admin).should be_admin<br />
(rdb:1) eval Person::ADMIN_GROUP<br />
#<Group id: 541702176, name: "Admin", created_at: "2009-08-09 18:17:26", updated_at: "2009-08-09 18:17:26"><br />
</code></p>
<h3>Running 'rake spec SPEC=spec/models/person_spec.rb':</h3>
<p><code><br />
[11:17:13 CITAlumni (48c51f1...)]$ rake spec SPEC=spec/models/person_spec.rb<br />
(in /Users/evan/Development/Ruby/CITAlumni)<br />
FF.....spec/models/person_spec.rb:64<br />
people(:admin).should be_admin<br />
(rdb:1) eval Person::ADMIN_GROUP<br />
nil<br />
</code></p>
<p>How very interesting ... when I use rake, that constant initializes to <code>nil</code>.    At some point, I'll actually get around to figuring out why this is so different when the specs are run via rake.   In the meantime, the fix was easy:</p>
<h2>The Solution</h2>
<p>The fix was just to refactor ADMIN_GROUP as a class method with a memoized instance variable.   This will at least limit DB queries for the admin group to one per page load; not quite as good as a single DB hit when the class is first loaded, but still a major improvement over querying for the admin group every time Person#admin? is called.  I moved it to the Group class at the same time, which was probably the right place for it in the first place:</p>
<p><code><br />
#app/models/group.rb:<br />
class Group < ActiveRecord::Base<br />
  def self.admin_group<br />
    @admin_group  ||= self.find_by_name('Admin')<br />
  end<br />
end</p>
<p>#app/models/person.rb<br />
class Group < ActiveRecord::Base<br />
  def admin?<br />
    groups.include? Group.admin_group<br />
  end<br />
end<br />
</code></p>
<p>And this worked just fine in all environments, solving the problem with 'rake spec'.</p>
<h2>The Moral</h2>
<p>Be careful with depending on behavior that occurs only during the loading of classes, as it can be environment-dependent!    </p>
<p>If anyone out there with uber Ruby skills knows exactly why running specs via rake prevents that class variable from loading correctly, please enlighten us in comments!</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lrdesign.com/2009/08/when-rake-spec-and-spec-spec-produce-different-results/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<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:
    funky_database_id:  0000012345
two:
    funky_database_id:  0000012346

The trouble with this 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><code><br />
one:<br />
    funky_database_id:  0000012345</p>
<p>two:<br />
    funky_database_id:  0000012346<br />
</code></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><code><br />
one:<br />
    funky_database_id:  "0000012345"</p>
<p>two:<br />
    funky_database_id:  "0000012346"<br />
</code></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lrdesign.com/2009/06/rails-fixture-strings-that-are-all-numbers/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</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>
		<slash:comments>0</slash:comments>
		</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><code>NoMethodError: undefined method `link_to' for #<br />
/Users/evan/Development/Ruby/eclipticdb/app/helpers/tasks_helper.rb:64:in `task_link'<br />
/Users/evan/Development/Ruby/eclipticdb/app/controllers/tasks_controller.rb:103:in `escalate'<br />
... etc ...<br />
</code></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><code>You have a nil object when you didn't expect it!<br />
The error occurred while evaluating nil.url_for</p>
<p>... some code here that calls a link_to ...</p>
<p>Trace of template inclusion: /tasks/_task_panel.html.erb, /tasks/_task_tabbed_panel.html.erb, /tasks/index.html.erb</p>
<p>RAILS_ROOT: /Users/evan/Development/Ruby/eclipticdb<br />
Application Trace | Framework Trace | Full Trace</p>
<p>vendor/rails/actionpack/lib/action_view/helpers/url_helper.rb:71:in `send'<br />
vendor/rails/actionpack/lib/action_view/helpers/url_helper.rb:71:in `url_for'</code></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>
		<slash:comments>1</slash:comments>
		</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>
		<slash:comments>0</slash:comments>
		</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><code>map.resources :tasks<br />
map.resources :action_items, :controller => 'tasks'<br />
map.resources :work_orders, :controller => 'tasks'<br />
map.resources :problem_reports, :controller => 'tasks'<br />
</code></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>
		<slash:comments>8</slash:comments>
		</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><code>class ActiveRecord::Base</p>
<p>  # Build and create records unsafely, bypassing attr_accessible.<br />
  # These methods are especially useful in tests and in the console.</p>
<p>  def self.unsafe_build(attrs)<br />
    record = new<br />
    record.unsafe_attributes = attrs<br />
    record<br />
  end</p>
<p>  def self.unsafe_create(attrs)<br />
    record = unsafe_build(attrs)<br />
    record.save<br />
    record<br />
  end</p>
<p>  def self.unsafe_create!(attrs)<br />
    unsafe_build(attrs).save!<br />
  end</p>
<p>  def unsafe_update_attributes!(attrs)<br />
    self.unsafe_attributes = attrs<br />
    self.save!<br />
  end</p>
<p>  def unsafe_update_attributes(attrs)<br />
    self.unsafe_attributes = attrs<br />
    self.save<br />
  end</p>
<p>  def unsafe_attributes=(attrs)<br />
    attrs.each do |k, v|<br />
      send("#{k}=", v)<br />
    end<br />
  end<br />
end</code></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lrdesign.com/2009/03/bypassing-mass-assignment-for-update_attributes/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</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 'LoansController POST 'create' with valid parameters should succeed'
undefined method `env' for 
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><code>NoMethodError in 'LoansController POST 'create' with valid parameters should succeed'<br />
undefined method `env' for <LoanRequest:0x3729e00></code></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><code>before(:each) do<br />
  ... some other stuff ...<br />
  @request = loan_requests(:johns_loan_request)  # fetch fixture<br />
end</code></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>
		<slash:comments>1</slash:comments>
		</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><code>#nav<br />
  li<br />
    :color #whatever<br />
    :float left</p>
<p>  a<br />
    :whatever etc<br />
</code></p>
<p>will compile to:<br />
<code>#nav li {<br />
    color: #whatever<br />
    float: left<br />
}<br />
#nav a {<br />
    whatever: etc<br />
}<br />
</code></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 />
<code>body #nav ul li a<br />
  :float left<br />
</code></p>
<p>or even<br />
<code>#content h1, #nav h2, .article h3, p h4<br />
  :font-weight bold<br />
</code> </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 />
<code><br />
!main_link_color = #48950a</p>
<p>a<br />
  :color= !main_link_color</p>
<p>#content h1<br />
  :border-width 0 0 1px 0<br />
  :border-color= !main_link_color<br />
</code></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>
		<slash:comments>5</slash:comments>
		</item>
	</channel>
</rss>
