简体   繁体   中英

How to refactor this Rails code?

Consider this helper method:

module SomeHelper

  def display_button
    Foo.find_by_id params[:id] and Foo.find(params[:id]).organizer.name != current_name and Foo.find(params[:id]).friends.find_by_name current_name
  end

end

How to refactor into something more readable?

Rails 3.2.2

Something like this?

module SomeHelper

  def display_button?
    if foo = Foo.find(params[:id])
      foo.organizer.name != current_name if foo.friends.find_by_name(current_name)
    end
  end

end

Note: if the helper method is returning a boolean, I would append the name with a ? ... ruby convention.

You can factorize the call to Foo.find(params[:id]) and use exists? for the third condition

module SomeHelper
  def display_button
    foo = foo.find_by_id params[:id]
    foo and foo.organizer.name != current_name and foo.friends.where(:name => current_name).exists?
  end
end

You can also create several methods to gain on reusability (and will save trouble if you model changes):

module SomeHelper
  def display_button
    foo = foo.find_by_id params[:id]
    foo && !is_organizer?(foo, current_name) && has_friend?(foo, current_name)
  end

  def is_organizer?(foo, name)
    foo.organizer.name == name
  end 

  def has_friend?(foo, name)
    foo.friends.where(:name => name).exists?
  end
end

try invokes the passed block on non-nil objects. Returns nil otherwise. So the return will be nil,true,false depending on your data.

def display_button
    Foo.find_by_id(params[:id]).try do |foo|
       foo.organizer.name != current_name && 
         foo.friends.find_by_name current_name
    end
  end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM