<?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"
	>

<channel>
	<title>Ruby Tutorials</title>
	<atom:link href="http://www.rubytutorials.net/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.rubytutorials.net</link>
	<description>Doctor's orders</description>
	<pubDate>Thu, 29 May 2008 07:03:50 +0000</pubDate>
	<generator>http://wordpress.org/?v=2.5</generator>
	<language>en</language>
			<item>
		<title>Configuring Cruisecontrol, Git and RSpec</title>
		<link>http://www.rubytutorials.net/2008/05/13/configuring-cruisecontrol-git-and-rspec/</link>
		<comments>http://www.rubytutorials.net/2008/05/13/configuring-cruisecontrol-git-and-rspec/#comments</comments>
		<pubDate>Tue, 13 May 2008 14:57:37 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[development]]></category>

		<category><![CDATA[cruisecontrol]]></category>

		<category><![CDATA[git]]></category>

		<category><![CDATA[rspec]]></category>

		<guid isPermaLink="false">http://www.rubytutorials.net/?p=18</guid>
		<description><![CDATA[The realization we needed a continuous integration server sank in good last week when work on our internal project really got started. The project has seen quite some development in the past, mainly when my skills in (RSpec) testing where, uhm, less than optimal. This on top of some high pressure hacking left the project [...]]]></description>
			<content:encoded><![CDATA[<p>The realization we needed a continuous integration server sank in good last week when work on our internal project really got started. The project has seen quite some development in the past, mainly when my skills in (RSpec) testing where, uhm, less than optimal. This on top of some high pressure hacking left the project in a pretty shabby shape. We are now working on it with three people and we&#8217;d like to introduce a bit more rigour in our development process.</p>
<p>One of the first steps was to use a continuous integration server. I was actually surprised so few existed and the choice for <a href="http://cruisecontrolrb.thoughtworks.com/">CruiseControl</a>(CC) was a quick one. This pretty piece of software did not support Git out of the box but there exists a <a href="http://github.com/benburkert/cruisecontrolrb/tree/master">GitHub branch</a> incorporating this functionality. What is even better is this <a href="http://codeintensity.blogspot.com/2008/04/setting-up-cruisecontrolrb-withfor-git.html">post</a> which explains how to use it! So I won&#8217;t go into the nitty gritty details, what I will do is point out some pit falls and how to make CruiseControl play nice with RSpec. Which it also does not support out of the box but which is really easy.</p>
<p>Install CC as per previously mentioned post. What threw me off where the <code>site_config.rb</code> and the <code>cruise_config.rb</code> I got the (wrong) impression that these files lived in the root directory of the CC install. This is <em>not </em>the case. When installing CC it, by default, creates a directory <code>~/.cruise</code> which holds your projects. It is here where the <code>site_config.rb</code> file lives. And this is the file to configure ActionMailer! And in  the directory <code>~/.cruise/projects/MyProject</code> the other file can be found in which to configure the people who need to receive emails when the build breaks.</p>
<p>When CC builds a project it just runs some Rake tasks, one of which is <code>cruise</code>. Getting CC to use RSpec is as simple a overwriting this task! This is what I gleaned from other posts:</p>
<pre name="code" class="ruby">

desc &quot;Task to do some preparations for CruiseControl&quot;
task :prepare do
RAILS_ENV = 'test'
end

desc &quot;Task for CruiseControl.rb, automatically picked up&quot;
task :cruise =&gt; [:prepare, &quot;db:migrate&quot;, &quot;spec&quot;] do

end
</pre>
<p>The first task is to make sure the test environment is used which is really what you want in a situation like this.</p>
<p>The next step would be to produce something more readable than the dump of the log file with the results of the ran RSpecs.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubytutorials.net/2008/05/13/configuring-cruisecontrol-git-and-rspec/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Using migrations to transform data</title>
		<link>http://www.rubytutorials.net/2008/04/28/using-migrations-to-transform-data/</link>
		<comments>http://www.rubytutorials.net/2008/04/28/using-migrations-to-transform-data/#comments</comments>
		<pubDate>Mon, 28 Apr 2008 10:00:54 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[rails]]></category>

		<category><![CDATA[migrations]]></category>

		<guid isPermaLink="false">http://www.rubytutorials.net/?p=17</guid>
		<description><![CDATA[Usually I use migrations to just add and remove columns. But today I needed to modify the database schema  of a live app and should thus preserve the data already present. Although not hard implementing it revealed some pitfalls.
The task at hand was to augment the users in the system with roles. We had [...]]]></description>
			<content:encoded><![CDATA[<p>Usually I use migrations to just add and remove columns. But today I needed to modify the database schema  of a live app and should thus preserve the data already present. Although not hard implementing it revealed some pitfalls.</p>
<p>The task at hand was to augment the users in the system with roles. We had a column in the Members table which made a member a manager or not(boolean). This information is now extracted to a roles table (we are using <a href="http://code.google.com/p/rolerequirement/">RoleRequirement</a>). It is now possible to assign many different roles to each member.</p>
<p>The migration I wrote at first looked something like this:</p>
<pre name="code" class="ruby">

def self.up
r = Role.new(:name =&gt; &quot;manager&quot;
r.save
remove_column :members, :manager
managers = Member.find_all_by_manager(true)
managers.each do |manager|
manager.roles &lt;&lt; r
manager.save
end
end
</pre>
<p>However this migration failed on the manager.save, complaining that the column manager on the table members no longer existed. And it didn&#8217;t of course. The column had just been removed! I figured that the attributes in the manager objects still contained the :manager =&gt; true key-value pair. So I deleted that but the error persisted. Which makes sense when I thought about it. The migration loaded the Rails framework with all inferred classes. One of these classes was the Member class which contained at the time of loading still a manager field. Trying to save the member without one of the attributes causes an error. Reloading framework seemed a bit overkill as well.</p>
<p>In the end the solution was, as most of the time, deceptively simple. Remove the column at the end of the migration!</p>
<pre name="code" class="ruby">

def self.up
r = Role.new(:name =&gt; &quot;manager&quot;)
r.save
managers = Member.find_all_by_manager(true)
managers.each do |manager|
manager.roles &lt;&lt; r
manager.save
end
remove_column :members, :manager
end
</pre>
<p>But how do you test your migration? I took a stab at this in the form of an RSpec test:</p>
<pre name="code" class="ruby">

describe Member, &quot;should migrate properly&quot; do
it &quot;should migrate correctly from a column manager to a role manager&quot; do

`rake db:drop`
`rake db:create`
`rake db:migrate VERSION=59`
m1 = Member.new(:manager =&gt; true)
m1.save_with_validation(false)
m2 = Member.new(:manager =&gt; true)
m2.save_with_validation(false)
m3 = Member.new(:manager =&gt; true)
m3.save_with_validation(false)
`rake db:migrate VERSION=60`
Member.find(m1.id).has_role ?(&quot;manager&quot;).should be_true
Member.find(m2.id).has_role?(&quot;manager&quot;).should be_true
Member.find(m3.id).has_role?(&quot;manager&quot;).should be_true
end
end
</pre>
<p>But this does not work yielding a MySQL timeout. This has to do with the fact that all tests are run in transaction mode preventing other database changes during the tests. This particular test waits for the lock to be released which never happens and thus times out.</p>
<p>I have yet to figure out how to do this, but I think this is really important! I would love to be able to test my migrations as these migrations manipulate live data which can not be lost. Any suggestions are welcome.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubytutorials.net/2008/04/28/using-migrations-to-transform-data/feed/</wfw:commentRss>
		</item>
		<item>
		<title>BackgroundRB versus Beanstalkd</title>
		<link>http://www.rubytutorials.net/2008/04/24/backgroundrb-versus-beanstalkd/</link>
		<comments>http://www.rubytutorials.net/2008/04/24/backgroundrb-versus-beanstalkd/#comments</comments>
		<pubDate>Thu, 24 Apr 2008 11:19:20 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[rails]]></category>

		<category><![CDATA[background]]></category>

		<guid isPermaLink="false">http://www.rubytutorials.net/?p=15</guid>
		<description><![CDATA[This seems to be a recurring problem. Sending a lot of emails from Rails is still a bit murky. You can&#8217;t really use ActiveMailer for this because when you are trying to send 12.000 emails the request does not return a respond until all the 12.000 emails are sent. This leads to confused users who [...]]]></description>
			<content:encoded><![CDATA[<p>This seems to be a recurring problem. Sending a lot of emails from Rails is still a bit murky. You can&#8217;t really use ActiveMailer for this because when you are trying to send 12.000 emails the request does not return a respond until all the 12.000 emails are sent. This leads to confused users who click the button again, timeouts etc etc. A general mess. You could use a cron job but that does not make that much sense as you would expect the emails being send as you press a button and not when a cron job comes along. Again confused users.</p>
<p>What you really want is to be able to background tasks and be done with it! For this there are many options. Unfortunately. But I believe the two candidates worth looking at are:</p>
<ul>
<li><a href="http://xph.us/software/beanstalkd/">beanstalkd</a></li>
<li><a href="http://backgroundrb.rubyforge.org/">backgroundrb</a></li>
</ul>
<p>Beanstalkd is being used on <a href="http://apps.facebook.com/causes/">Facebook</a>(need I say more?). BackgroundRB enjoys more attention and has recently been rewritten and thus presumably increased in quality.  The first is not as tightly coupled with Rails as the latter but that can be amended with a  <a href="http://async-observer.rubyforge.org/">plugin</a>.</p>
<p>Then there is the matter of compiling beanstalkd&#8230; That was no fun at all. Well maybe I made it too hard for my self and I did not exactly knew how to manipulate &#8216;make&#8217;. But I wanted the latest version(0.11) of beanstalkd and MacPorts only had 0.9 in stock. So I downloaded the source, followed the readme and hit make. Of course that didn&#8217;t fly. I needed to point the makefile to the correct lib directory. Long story short, I <em>did</em> install beanstalkd through port and took the makefile from that install and patched the makefile in the source download. Here is the patched  <a href="http://www.rubytutorials.net/wp-content/makefilepatched.txt">makefile</a>. This worked like a charm! However this made me a bit concerned how up to date the packages on our Debian staging server were. It turned out that I needed to install both the dependencies and the actual beanstalkd from source. I&#8217;d prefer gems then.</p>
<p>For more information on beanstalkd I gladly refer to <a href="http://nubyonrails.com/articles/about-this-blog-beanstalk-messaging-queue">this blog post</a> as I decided after this ordeal that I would go forward with backgroundrb. This decision was mainly based on the better logging abilities of backgroundrb and the from source install as opposed to some gems.</p>
<p>A parting thought; look at the footer of backgroundrb&#8217;s website. Notice the link called Ginger Ninja? Click it. I think it&#8217;s at least weird and perhaps doggy.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubytutorials.net/2008/04/24/backgroundrb-versus-beanstalkd/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Small Rspec revelations, RJS</title>
		<link>http://www.rubytutorials.net/2008/02/29/small-rspec-revelations-rjs/</link>
		<comments>http://www.rubytutorials.net/2008/02/29/small-rspec-revelations-rjs/#comments</comments>
		<pubDate>Fri, 29 Feb 2008 13:44:17 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[rjs]]></category>

		<category><![CDATA[rspec]]></category>

		<guid isPermaLink="false">http://www.rubytutorials.net/2008/02/29/small-rspec-revelations-rjs/</guid>
		<description><![CDATA[The closing scene of this series. Specing RJS templates. Again a topic which is not on the forefront of the RSpec community.  And again a blog post saved the day. It took me a little bit of time for figure out what kind of RJS type the response object should expect. To illustrate an example [...]]]></description>
			<content:encoded><![CDATA[<p>The closing scene of this series. Specing RJS templates. Again a topic which is not on the forefront of the RSpec community.  And again a <a href="http://jonathan.tron.name/articles/2007/11/24/rspec-and-inline-rjs">blog post</a> saved the day. It took me a little bit of time for figure out what kind of RJS type the response object should expect. To illustrate an example RSpec:</p>
<pre name="code" class="ruby">

response.should have_rjs(:chained_replace_html, &quot;some_id&quot;) do
response.should have_text(/some random text/)
end
</pre>
<p>The response object should have an RJS object but what type? According to the <a href="http://noobkit.com/show/ruby/rails/rails-edge/actionpack-edge/actioncontroller/assertions/selectorassertions/assert_select_rjs.html">assert_select_rjs</a> method, which the have_rjs method wraps, there are only a hand full of these types but apparently not all of them are listed. As I found out when my inline RJS:</p>
<pre name="code" class="ruby">

render :update do |page|
page[update_div].update(text)
end
</pre>
<p>None of the mentioned types responded correctly. But I noticed that the blog post mentioned earlier used an other type. Browsing through the source code of assert_select_rjs I found my missing type: chained_replace_html. Hooray! Everything worked fine and dandy from there on.</p>
<p>One last hiccup was that code in the block passed to the have_rjs method does not scope by default the response.should directive, so this is wrong:</p>
<pre name="code" class="ruby">

response.should have_rjs(:chained_replace_html, &quot;some_id&quot;) do
have_text(/some random text/)
end
</pre>
<p>Obviously.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubytutorials.net/2008/02/29/small-rspec-revelations-rjs/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Small Rspec revelations, Modules</title>
		<link>http://www.rubytutorials.net/2008/02/27/small-rspec-revelations-modules/</link>
		<comments>http://www.rubytutorials.net/2008/02/27/small-rspec-revelations-modules/#comments</comments>
		<pubDate>Wed, 27 Feb 2008 13:08:50 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[modules]]></category>

		<category><![CDATA[rspec]]></category>

		<guid isPermaLink="false">http://www.rubytutorials.net/?p=12</guid>
		<description><![CDATA[It looks like this is going to be a three parter. For our current project we wanted to abstract some of the functionality which appeared in our models to a module. As we are taking TDD more seriously nowadays I set out to write a spec for  the module first. Right. For a normal [...]]]></description>
			<content:encoded><![CDATA[<p>It looks like this is going to be a three parter. For our current project we wanted to abstract some of the functionality which appeared in our models to a module. As we are taking TDD more seriously nowadays I set out to write a spec for  the module first. Right. For a normal spec you need an instance of the object you are specing. But by their very nature models can not be instantiated! So how to write a spec then? Here you go:</p>
<pre name="code" class="ruby">

before(:each) do
klass = Class.new { include FicklePricing }
@foo = klass.new
@foo.stub!(:id).and_return(1)
end
</pre>
<p>In this case we have created a class with does nothing but to include our module. And this almost empty class can by instantiated and used in this specs. Trivial example:</p>
<pre name="code" class="ruby">

it &quot;should respond_to price method&quot; do
@item.should respond_to(:get_price)
end
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.rubytutorials.net/2008/02/27/small-rspec-revelations-modules/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Small Rspec revelations, ActionMailer</title>
		<link>http://www.rubytutorials.net/2008/02/26/small-rspec-revelations-actionmailer/</link>
		<comments>http://www.rubytutorials.net/2008/02/26/small-rspec-revelations-actionmailer/#comments</comments>
		<pubDate>Tue, 26 Feb 2008 16:45:08 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<category><![CDATA[mailer]]></category>

		<category><![CDATA[rspec]]></category>

		<guid isPermaLink="false">http://www.rubytutorials.net/?p=11</guid>
		<description><![CDATA[At the office we are getting more and more serious about RSpec . Today we ran into two things we had not done so far. Specing an ActionMailer and a module. The Rails Way only covered Test::Unit and that looked dreadful. Way to much code. I still think I should be coding applications not tests. [...]]]></description>
			<content:encoded><![CDATA[<p>At the office we are getting more and more serious about <a href="http://rspec.info">RSpec</a> . Today we ran into two things we had not done so far. Specing an ActionMailer and a module. The Rails Way only covered Test::Unit and that looked dreadful. Way to much code. I still think I should be coding applications not tests. A quick google turned up not so much, nor did the RSpec site help. Fortunately someone on the <a href="http://rubyforge.org/pipermail/rspec-users/2007-February/000662.html">RSpec mailinglist</a> brought the subject up. With that I knew enough to get the tests working.</p>
<pre name="code" class="ruby">

before(:each) do
ActionMailer::Base.delivery_method = :test
ActionMailer::Base.perform_deliveries = true
ActionMailer::Base.deliveries = []
end
</pre>
<p>This before block set the method for delivery method to :test. Normally it default to :smtp and an other possibility is :sendmail. The second directive tells ActionMailer to actually send the emails(who would have guessed?). The deliveries array keeps track of every email sent.</p>
<p>Now you can just send your email as you usually would:</p>
<pre name="code" class="ruby">

mail = Notifications.deliver_some_random_email(&quot;name&quot;)
ActionMailer::Base.deliveries.size.should == 1
mail.body.should =~ /name/
</pre>
<p>Rock on RSpec.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubytutorials.net/2008/02/26/small-rspec-revelations-actionmailer/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Building a RESTful CMS</title>
		<link>http://www.rubytutorials.net/2008/02/21/building-a-restful-cms/</link>
		<comments>http://www.rubytutorials.net/2008/02/21/building-a-restful-cms/#comments</comments>
		<pubDate>Thu, 21 Feb 2008 16:43:45 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.rubytutorials.net/?p=10</guid>
		<description><![CDATA[Today is the day we at Innovationfactory finish the development of a site maintained by a CMS. As this was the first CMS we build in RESTful Rails initially we where unsure how to proceed. There is some discussion(and  here and here) on whether or not the admin functionality should be seperated from the [...]]]></description>
			<content:encoded><![CDATA[<p>Today is the day we at <a href="www.innovationfactory.nl">Innovationfactory</a> finish the development of a site maintained by a CMS. As this was the first CMS we build in RESTful Rails initially we where unsure how to proceed. There is some <a href="http://www.fallenrogue.com/articles/178-Creating-a-RESTful-admin-section-in-Rails">discussion</a>(and  <a href="http://www.fallenrogue.com/articles/181-Creating-a-RESTful-admin-section-in-Rails-with-2-controllers">here</a> and <a href="http://www.akitaonrails.com/2007/12/12/rolling-with-rails-2-0-the-first-full-tutorial">here</a>) on whether or not the admin functionality should be seperated from the non admin functionality. On one hand this makes sense. As an admin you are doing something vastly different than a normal user visiting the site. On the other hand it doesn&#8217;t. Both the admin and visitor interact with the same resources. Only the view and options presented are differtent. In the end we choose to seperate the admin functionality from the visitors functionality, thus creating two controllers for one resource. We deemed this better as the underlying resource is still the same but the interaction is different. And interaction is taken care of in a controller. Hence two controllers for two distinct way of interacting with our resources.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubytutorials.net/2008/02/21/building-a-restful-cms/feed/</wfw:commentRss>
		</item>
		<item>
		<title>The usage of self in Ruby</title>
		<link>http://www.rubytutorials.net/2008/01/01/the-usage-of-self-in-ruby/</link>
		<comments>http://www.rubytutorials.net/2008/01/01/the-usage-of-self-in-ruby/#comments</comments>
		<pubDate>Tue, 01 Jan 2008 16:40:08 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.rubytutorials.net/?p=9</guid>
		<description><![CDATA[This confused me for some time and I figured I write it down for others to enjoy. When should one use the keyword self in AR:B? For this it is important to realise that Ruby is an interpreted language. Whenever Ruby sees an assignment like bla = 'boe' it first looks for a local varialbe [...]]]></description>
			<content:encoded><![CDATA[<p>This confused me for some time and I figured I write it down for others to enjoy. When should one use the keyword self in AR:B? For this it is important to realise that Ruby is an interpreted language. Whenever Ruby sees an assignment like <code>bla = 'boe'</code> it first looks for a local varialbe by that name(<code>bla</code> in this case) and if that does not exists it then looks for a method <code>bla=</code></p>
<pre name="code" class="ruby">

class Foo
  def bar
    text = 'fake' #assigns a variable 'text'
    text.gsub!() #changes the variable 'text'
  end

  def bla
    text.gsub!() #does not find a variable 'text', then searches for a method 'text'(and fails in this case)
  end
end
</pre>
<p>So if you want to change a field in an ActiveRecord model you need to tell Ruby not to create a local variable but to use the generated setter method.</p>
<pre name="code" class="ruby">

class Foo &lt; AR:B
  def bar
    self.text = 'fake' #assigns the field 'text'
    text.gsub!() #changes the variable 'text'
  end
end
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.rubytutorials.net/2008/01/01/the-usage-of-self-in-ruby/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Modules, inheritance and classes</title>
		<link>http://www.rubytutorials.net/2007/12/12/modules-inheritance-and-classes/</link>
		<comments>http://www.rubytutorials.net/2007/12/12/modules-inheritance-and-classes/#comments</comments>
		<pubDate>Wed, 12 Dec 2007 16:37:54 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.rubytutorials.net/?p=8</guid>
		<description><![CDATA[I can be a bit of a purist when it comes to programming. I love to have my code DRY and go to lengths to achieve that. Today I wrote a piece of code which would enable the duplication of Rails models. This in order to support some templating. Well it&#8217;s a little bit more [...]]]></description>
			<content:encoded><![CDATA[<p>I can be a bit of a purist when it comes to programming. I love to have my code DRY and go to lengths to achieve that. Today I wrote a piece of code which would enable the duplication of Rails models. This in order to support some templating. Well it&#8217;s a little bit more than &#8217;some&#8217; as I need to copy the entire model with all associated models(and their associated models, and their &#8230;). To keep things flexible I did not wanted to loop over a couple predefined fields and do all the copying there:</p>
<pre name="code" class="ruby">

copy = Project.new
p = Project.find(:first)
copy.title = p.title
copy.description = p.description
p.members.each do |member|
  copy.members.build(:name =&gt; member.name, :function =&gt; member.function)
end
</pre>
<p>This is prone to errors not to mention ugly(and a lot of dumb work). </p>
<p>So I figured I&#8217;d write something better. This was quickly done:</p>
<pre name="code" class="ruby">

class Project &lt; AR:B
  cattr_accessor :non_duplicatable_columns
  non_duplicatable_columns = [primary_key, 'created_at', 'updated_at','created_on', 'updated_on'] + column_names.select {|column_name| column_name =~ /_id$/}      

  def copy
    copy_columns = self.class.column_names - self.class.non_duplicatable_columns
    a = Hash.new
    copy_columns.each {|cc| a[cc] = self.send(cc) }
    clone = Project.create(a)
  end
end
</pre>
<p>But I needed this piece of functionality in several models. So what&#8217;s a good programmer to do? Refactor the code into a module of course! But there I hit some snags. The method <tt>cattr_accessor</tt>, for example, is a bit of a strange beast. It is not documented but is should be read like &#8216;class attribute accessor&#8217;. The method creates <em>class instance methods</em>. This is something different from <em>instance methods</em> which you usually use. Instance methods are callable on an object which is instance of a class. </p>
<pre name="code" class="ruby">

p = Project.new #class instance method
p.copy #instance method
</pre>
<p>Defining class instance methods goes with the
<pre>self</pre>
<p> keyword. It reminded me of the Java static keyword.</p>
<pre name="code" class="ruby">

def self.foo
  #do something, can be called as: FullClassName.foo
end
</pre>
<p>Keep the eye on the ball here, <tt>self</tt> points to the object on which this method is called. When defining the copy method the method column_names is called but this is a class instance method from the class subclassing AR:B. So the objects looks at it<tt>self</tt>, asks who the fathering <tt>class</tt> is and calls the desired method from that class. </p>
<p>The method
<pre>cattr_accessor</pre>
<p> can no longer float freely in the class definition. It needs a container as the module is read at the moment the Rails stack is initialize and at that point the module is not necessarily hooked into a class in which a <tt>cattr_accessor</tt> makes sense. Luckily the module &#8220;http://ruby-doc.org/core/classes/Module.html&#8221;:Module defines a method <tt>included</tt> which is called whenever the module is, well, included. Using this we can still define the
<pre>non_duplicatable_columns</pre>
<p> on a per model basis. </p>
<p>Finalized the module looks like this(stored in lib/duplicatable.rb):</p>
<pre name="code" class="ruby">

module Duplicatable

  def Duplicatable.included(base)
    base.cattr_accessor :non_duplicatable_columns
    base.non_duplicatable_columns = [base.primary_key, 'created_at', 'updated_at','created_on', 'updated_on'] + base.column_names.select {|column_name| column_name =~ /_id$/}
  end

  def copy
    copy_columns = self.class.column_names - self.class.non_duplicatable_columns
    a = Hash.new
    copy_columns.each {|cc| a[cc] = self.send(cc) }
    clone = self.class.create(a)
  end
end
</pre>
<p>And a simple <tt>include Duplicatable</tt> adds all its functionality to a model.<br />
Why not use a super class here? That would require calling a initialize function(to set the non_duplicatable_columns) in each model with would extend this super class. Which would result in more code and thus more places where this can break.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.rubytutorials.net/2007/12/12/modules-inheritance-and-classes/feed/</wfw:commentRss>
		</item>
		<item>
		<title>Living on the Edge</title>
		<link>http://www.rubytutorials.net/2007/12/10/living-on-the-edge/</link>
		<comments>http://www.rubytutorials.net/2007/12/10/living-on-the-edge/#comments</comments>
		<pubDate>Mon, 10 Dec 2007 16:29:51 +0000</pubDate>
		<dc:creator>admin</dc:creator>
		
		<category><![CDATA[Uncategorized]]></category>

		<guid isPermaLink="false">http://www.rubytutorials.net/?p=7</guid>
		<description><![CDATA[As a Rails developer I am still a bit wet behind the ears. Following the lead of a more senior developer I picked up the habit of developing all(that is four so far) applications in Rails Edge with the help of RSpec, Edge RSpec.
Last weekend I picked up a pet project which a colleague and [...]]]></description>
			<content:encoded><![CDATA[<p>As a Rails developer I am still a bit wet behind the ears. Following the lead of a more senior developer I picked up the habit of developing all(that is four so far) applications in Rails Edge with the help of RSpec, Edge RSpec.</p>
<p>Last weekend I picked up a pet project which a colleague and I came up with. Nothing difficult and we figured we could get this done within the week. Boy was I wrong. Setting the whole thing up took me the better part of the day. Of course partially due to my own inexperience but the fact that I was using Edge for everything didn&#8217;t help.</p>
<p>I&#8217;ll skip all the things which went horribly wrong, this is what I _should_ have done:</p>
<pre name="code" class="ruby">

$ rails new_prj
$ cd new_prj
$ piston import http://dev.rubyonrails.org/svn/rails/trunk vendor/rails
$ piston import svn://rubyforge.org/var/svn/rspec/trunk/rspec vendor/plugins/rspec
$ piston import svn://rubyforge.org/var/svn/rspec/trunk/rspec_on_rails vendor/plugins/rspec_on_rails
$ ./script/generate rspec
</pre>
<p>Don&#8217;t try to freeze rails using rake rails:freeze:edge. This leads to pain and the absence of a framework dependency causing the ./script/server command to fail.<br />
Don&#8217;t try to use the current release of RSpec in combination with the edge version of Rails. This again leads to suffering and mysteriously failing tests.<br />
Don&#8217;t forget that running ./script/generate rspec_model is not enough to get the entire RSpec framework to behave. It&#8217;ll work to some degree but has some crucial functionality missing. For example the ./script/spec command is missing.<br />
Don&#8217;t expect <a href="http://weblog.techno-weenie.net/2006/8/1/restful-authentication-plugin">Restful authentication</a> to play nice with RSpec through <a href="http://www.vaporbase.com/postings/126">Vaporbase&#8217;s</a> spec files. Don&#8217;t get me wrong the guys of Vaporbase did a great job it just didn&#8217;t work for me. The class UserNotifier should be UserMailer in my instance and the protected helper methods in the sessions_controller_spec.rb are ran by rspec throwing weird errors. So these should be moved to the spec_helper.rb file.</p>
<p>As a final bonus, ever wanted to spec a single file?</p>
<pre name="code" class="ruby">

$ ./script/spec spec/controllers/foo_controller_spec.rb --color -b
</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.rubytutorials.net/2007/12/10/living-on-the-edge/feed/</wfw:commentRss>
		</item>
	</channel>
</rss>
