<?xml version="1.0" encoding="UTF-8"?>
<feed xml:lang="en-US" xmlns="http://www.w3.org/2005/Atom">
  <id>tag:www.refactormycode.com,2007:users569</id>
  <link type="application/atom+xml" href="http://www.refactormycode.com/users/569" rel="self"/>
  <title>Fabien Jakimowicz</title>
  <updated>Wed Jul 07 11:03:17 -0700 2010</updated>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor518530</id>
    <published>2010-07-07T11:03:17-07:00</published>
    <title>[Ruby] On val.respond_to? x, but val.x is undefind for val?</title>
    <content type="html">&lt;p&gt;If your are in Rails project, take a look at HashWithIndifferentAccess&lt;/p&gt;

&lt;pre&gt;h = {:asdf =&amp;gt; 'toto', :titi =&amp;gt; 42}
 =&amp;gt; {:asdf=&amp;gt;&amp;quot;toto&amp;quot;, :titi=&amp;gt;42}
h2 = HashWithIndifferentAccess.new(h)
 =&amp;gt; {&amp;quot;titi&amp;quot;=&amp;gt;42, &amp;quot;asdf&amp;quot;=&amp;gt;&amp;quot;toto&amp;quot;}
h2[:titi]
 =&amp;gt; 42
h2['titi']
 =&amp;gt; 42&lt;/pre&gt;</content>
    <author>
      <name>Fabien Jakimowicz</name>
      <email>fabien@jakimowicz.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/1347-val-respond_to-x-but-val-x-is-undefind-for-val/refactors/518530" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor152816</id>
    <published>2009-03-24T12:42:26-07:00</published>
    <title>[Ruby] On Validate the nested model</title>
    <content type="html">&lt;p&gt;I'm not sure why you need to manually validate each questions since ActiveRecord should validate them before saving.&lt;/p&gt;

&lt;p&gt;Anyway, here is a better way to do it.&lt;/p&gt;

&lt;pre&gt;## Round model
class Round &amp;lt; ActiveRecord::Base
  belongs_to :season
  has_many :questions, :dependent =&amp;gt; :destroy

  def validate
    errors.add(&amp;quot;questions&amp;quot;, &amp;quot;are invalid&amp;quot;) unless questions.all? {|q| q.valid?}
  end
end

## Question model
class Question &amp;lt; ActiveRecord::Base
  belongs_to :round
end

## Rounds controller
class RoundsController &amp;lt; ApplicationController
  def publish
    @round = @season.rounds.find(params[:id])
    @round.update_attributes! :published =&amp;gt; true
    flash[:notice] = 'Round was successfully published.'
  rescue ActiveRecord::RecordInvalid
    flash[:notice] = 'Round has invalid questions.'
  ensure
    redirect_to season_round_path(@round.season, @round)
  end
end&lt;/pre&gt;</content>
    <author>
      <name>Fabien Jakimowicz</name>
      <email>fabien@jakimowicz.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/799-validate-the-nested-model/refactors/152816" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor148713</id>
    <published>2009-02-25T14:20:43-08:00</published>
    <title>[Ruby] On Too many for loops</title>
    <content type="html">&lt;p&gt;You can optimize a little bit your code but you will have to modify your models.
&lt;br /&gt;Take a look at :through argument in ActiveRecord::Base/has_many documentation.&lt;/p&gt;

&lt;p&gt;PS: if you precise a little bit your models and relations, maybe we can find a better solution&lt;/p&gt;

&lt;pre&gt;## User model
class User &amp;lt; ActiveRecord::Base
  has_many :classrooms
  has_many :assignments, :through =&amp;gt; :classrooms
end

## Users Controller
class UsersController &amp;lt; ApplicationController
  def dashboard    
    @submitted_assignments = Assignment.find(:all, :joins =&amp;gt; :student_assignments)
    @assignments = current_user.assignments
  end
end

## View: dashboard.html.haml

- for assignment in @assignments
  - for sa in assignment.student_assignments
    = sa.id&lt;/pre&gt;</content>
    <author>
      <name>Fabien Jakimowicz</name>
      <email>fabien@jakimowicz.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/768-too-many-for-loops/refactors/148713" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor147114</id>
    <published>2009-02-14T10:46:29-08:00</published>
    <title>[Ruby] On Re-Refactor Mailer Conditions</title>
    <content type="html">&lt;p&gt;You should use callbacks and exceptions ;)&lt;/p&gt;

&lt;p&gt;I consider your current_account.announcements as Announcement model, and the current_account leads to a user model.&lt;/p&gt;

&lt;pre&gt;## Announcement model
class Announcement &amp;lt; ActiveRecord::Base
  ANNONCEMENT_TYPES = {'squad'    =&amp;gt; :deliver_squad_announcement,
                       'everyone' =&amp;gt; :deliver_general_announcement,
                       'tryout'   =&amp;gt; :deliver_general_announcement}

  belongs_to :user

  after_create :deliver_announcement

  def deliver_announcement
    AnnouncementMailer.send ANNONCEMENT_TYPES[sent_to], self, user
  end
end

## Controller code
def create
  @announcement = current_account.announcements.build(params[:announcement])
  @announcement.save!
  flash[:notice] = 'Announcement was successfully created.'
  respond_to do |format|
    format.html { redirect_to(@announcement) }
    format.xml  { render :xml =&amp;gt; @announcement, :status =&amp;gt; :created, :location =&amp;gt; @announcement }
  end
rescue ActiveRecord::RecordInvalid
  flash.now[:error] = 'Something went wrong.'
  respond_to do |format|
    format.html { render :action =&amp;gt; &amp;quot;new&amp;quot; }
    format.xml  { render :xml =&amp;gt; @announcement.errors, :status =&amp;gt; :unprocessable_entity }
  end
end&lt;/pre&gt;</content>
    <author>
      <name>Fabien Jakimowicz</name>
      <email>fabien@jakimowicz.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/755-re-refactor-mailer-conditions/refactors/147114" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor146904</id>
    <published>2009-02-12T13:34:06-08:00</published>
    <title>[Ruby] On While loop to get unique value</title>
    <content type="html">&lt;p&gt;If you are using ActiveRecord and if your database supports it you should use unique indexes.&lt;/p&gt;

&lt;pre&gt;## Index creation
add_index(:vouchers, [:vouchercode], :unique =&amp;gt; true)

## Voucher model
class Voucher &amp;lt; ActiveRecord::Base
  def create_or_update
    super
  rescue ActiveRecord::StatementInvalid =&amp;gt; e
    if e.to_s =~ %r{index_vouchers_on_vouchercode}i
      self.vouchercode = generate_vouchercode(8)
      retry
    else
      raise
    end
  end
end  &lt;/pre&gt;</content>
    <author>
      <name>Fabien Jakimowicz</name>
      <email>fabien@jakimowicz.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/697-while-loop-to-get-unique-value/refactors/146904" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor146899</id>
    <published>2009-02-12T12:36:28-08:00</published>
    <title>[Bash] On Unzip large database dump directly into mysql</title>
    <content type="html">&lt;p&gt;Not really better, but you save a few keystrokes.&lt;/p&gt;

&lt;pre&gt;zcat database_dump.sql.gz | mysql -u username -h host -p password database&lt;/pre&gt;</content>
    <author>
      <name>Fabien Jakimowicz</name>
      <email>fabien@jakimowicz.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/753-unzip-large-database-dump-directly-into-mysql/refactors/146899" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor14689</id>
    <published>2008-08-09T11:34:30-07:00</published>
    <title>[Ruby] On Caesar Cipher</title>
    <content type="html">

&lt;pre&gt;def caesar(text, shift)
  text.split('').collect {|letter| (letter[0] + shift).chr}.join
end&lt;/pre&gt;</content>
    <author>
      <name>Fabien Jakimowicz</name>
      <email>fabien@jakimowicz.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/427-caesar-cipher/refactors/14689" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor14439</id>
    <published>2008-08-03T12:48:33-07:00</published>
    <title>[Ruby] On Rails - Multiple instances and folder creation</title>
    <content type="html">&lt;p&gt;You should move a lot of logic down to models.&lt;/p&gt;

&lt;p&gt;In this code, you should add some checks on folder creation and folder deletion on website/account destroy. You can also reduce controller code by nesting forms (user and website will be in account params hash) and using an after_create on account model to create user and website. But this could be overkill ;)&lt;/p&gt;

&lt;pre&gt;## Account model
class Account &amp;lt; ActiveRecord::Base
  has_many :websites
  has_many :users

  validates_presence_of :name

  before_create :make_short_name

  private
  def make_short_name
    self.short_name = name.gsub(/\W+|\s+/, '-').downcase
  end
end

## Website model
class Website &amp;lt; ActiveRecord::Base
  belongs_to :account

  validates_presence_of :name
  validates_associated :account # we rely on account short_name, we must check it
  validates_uniqueness_of :short_name, :scope =&amp;gt; :account_id # You could have some surprises with your folders if you don't check it

  before_create :make_short_name
  after_create :make_base_folders

  Folders = %w{docs pictures users}

  private
  def make_short_name
    self.short_name = name.gsub(/\W+|\s+/, '-').downcase
  end

  def make_base_folders
    Folders.each {|folder_name| FileUtils.mkdir_p &amp;quot;#{RAILS_ROOT}/public/content/#{account.short_name}/#{short_name}/#{folder_name}&amp;quot;}
  end
end
## User model
class User &amp;lt; ActiveRecord::Base
  belongs_to :account

  validates_associated :account
end
## Controller
def create
  @account = Account.create!(params[:account])
  @user = @account.users.create!(params[:user])
  @website = @account.websites.create!(params[:website])
  flash[:notice] = 'Your account was successfully created. Please login to begin :)'
  redirect_to login_path
rescue
  render :layout =&amp;gt; 'signup', :action =&amp;gt; 'new'
end&lt;/pre&gt;</content>
    <author>
      <name>Fabien Jakimowicz</name>
      <email>fabien@jakimowicz.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/417-rails-multiple-instances-and-folder-creation/refactors/14439" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor14209</id>
    <published>2008-07-31T13:33:31-07:00</published>
    <title>[Ruby] On How to make instance variable Persistent in between actions</title>
    <content type="html">&lt;p&gt;You can use a before filter to avoid code duplication.&lt;/p&gt;

&lt;p&gt;But keeping 'dynamic' data between queries is not always a good idea : data can change between 2 queries and you can have inconsistent data.&lt;/p&gt;

&lt;p&gt;Anyway, you can use session to store data between queries. Here are 2 solutions.&lt;/p&gt;

&lt;p&gt;You can even remove action definition if there are empty, but you will loose code clarity&lt;/p&gt;

&lt;pre&gt;## avoiding code duplication
class MyaccountController &amp;lt; ApplicationController
  before_filter :load_users, :only =&amp;gt; [ 'account_details', 'show_email_box', 'show_mobile_box' ]
    
  def account_details
  end
  
  def show_email_box
  end
  
  def show_mobile_box
  end

  private
  def load_users
    @users = User.find(:all,:conditions=&amp;gt;&amp;quot;age &amp;gt; #{current_user.age}&amp;quot;)
  end
  
end

## persistent storage between queries in session
class MyaccountController &amp;lt; ApplicationController
  before_filter :load_users, :only =&amp;gt; [ 'account_details', 'show_email_box', 'show_mobile_box' ]
    
  def account_details
  end
  
  def show_email_box
  end
  
  def show_mobile_box
  end

  private
  def load_users
    session[:users] ||= User.find(:all,:conditions=&amp;gt;&amp;quot;age &amp;gt; #{current_user.age}&amp;quot;)
    @users = session[:users]
  end
  
end&lt;/pre&gt;</content>
    <author>
      <name>Fabien Jakimowicz</name>
      <email>fabien@jakimowicz.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/411-how-to-make-instance-variable-persistent-in-between-actions/refactors/14209" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor14052</id>
    <published>2008-07-29T22:21:27-07:00</published>
    <title>[Ruby] On Saving multiple models in one action</title>
    <content type="html">&lt;p&gt;there is a lot of way to clean this, but without any other information (relation type between @foo and bar, form, ...) i can just propose something using exceptions and transactions.&lt;/p&gt;

&lt;p&gt;A transaction will roll back any modifications if there is any failure. In your case, you need to save both instances only if both of them are valid. If one fail, the entire transaction will fail and nothing will be saved&lt;/p&gt;

&lt;pre&gt;def update_foo_and_bar
  # You can also use @foo.class.transaction and @foo.bar.class.transaction if you have multiple database at the same time
  ActiveRecord::Base.transaction {@foo.update_attributes!(params[:foo]) and @foo.bar.update_attributes!(params[:bar])}
  redirect_to foo_url(@parent)
rescue ActiveRecord::RecordNotSaved
  render :action =&amp;gt; 'edit'
end&lt;/pre&gt;</content>
    <author>
      <name>Fabien Jakimowicz</name>
      <email>fabien@jakimowicz.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/403-saving-multiple-models-in-one-action/refactors/14052" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor13121</id>
    <published>2008-07-14T23:38:12-07:00</published>
    <title>[Ruby] On cleaner way to limit results from xml </title>
    <content type="html">&lt;p&gt;i'm not familiar with REXML library, but in the api doc there is a function to_a, you should give it a try.&lt;/p&gt;

&lt;pre&gt;xml = REXML::Document.new(data)

artists = xml.elements.to_a('//artist')[0..limit].collect do |artist|
{&amp;quot;name&amp;quot; =&amp;gt; artist.elements['name'].text
end&lt;/pre&gt;</content>
    <author>
      <name>Fabien Jakimowicz</name>
      <email>fabien@jakimowicz.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/365-cleaner-way-to-limit-results-from-xml/refactors/13121" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor13118</id>
    <published>2008-07-14T23:23:43-07:00</published>
    <title>[Ruby] On Python's enumerate in Ruby?</title>
    <content type="html">

&lt;pre&gt;['foo', 'bar', 'baz'].each_with_index {|j, i| puts &amp;quot;#{i} #{j}&amp;quot;}&lt;/pre&gt;</content>
    <author>
      <name>Fabien Jakimowicz</name>
      <email>fabien@jakimowicz.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/368-python-s-enumerate-in-ruby/refactors/13118" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor11021</id>
    <published>2008-06-17T15:32:51-07:00</published>
    <title>[Ruby] On collecting attributes from find(: all) method</title>
    <content type="html">&lt;p&gt;I thought the same about html select rails helper but it was supposed to render it flatten, so be it ;)&lt;/p&gt;

&lt;pre&gt;&lt;/pre&gt;</content>
    <author>
      <name>Fabien Jakimowicz</name>
      <email>fabien@jakimowicz.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/330-collecting-some-attribute-from-find-all-method/refactors/11021" rel="alternate"/>
  </entry>
  <entry>
    <id>tag:www.refactormycode.com,2007:Refactor10992</id>
    <published>2008-06-17T11:52:32-07:00</published>
    <title>[Ruby] On collecting attributes from find(: all) method</title>
    <content type="html">

&lt;pre&gt;# Rails &amp;lt; 2.0
Carrier.find(:all).collect {|d| [d.id, d.name]}.flatten

# Rails &amp;gt;= 2.0.2
Carrier.all.collect {|d| [d.id, d.name]}.flatten&lt;/pre&gt;</content>
    <author>
      <name>Fabien Jakimowicz</name>
      <email>fabien@jakimowicz.com</email>
    </author>
    <link type="text/html" href="http://www.refactormycode.com/codes/330-collecting-some-attribute-from-find-all-method/refactors/10992" rel="alternate"/>
  </entry>
</feed>

