Ruby中更漂亮的代码

时间:2011-07-05 17:38:34

标签: ruby ruby-on-rails-3

这段代码是否有更漂亮的版本?

@available_option_types.delete_if {|ot|
  result = true 
  result = current_user.retailer.id != ot.retailer.id if ot.retailer.present? 
  result
} unless current_user.has_role? 'admin'

谢谢!

4 个答案:

答案 0 :(得分:3)

unless current_user.has_role? 'admin'
  @available_option_types.delete_if do |ot|
    !ot.retailer.present? ||
      (ot.retailer.present? &&
        current_user.retailer.id != ot.retailer.id)
  end
end

答案 1 :(得分:3)

@available_option_types.delete_if { |ot|
  ot.retailer.present? ? (current_user.retailer.id != ot.retailer.id) : true
} unless current_user.has_role? 'admin'

如果你在模型中添加一些逻辑,它会更漂亮:

class User
  def same_retailer_with?(option_type)
    option_type.retailer.present? ? (self.retailer.id != option_type.retailer.id) : true
  end
end

@available_option_types.delete_if { |ot| current_user.same_retailer_with?(ot) } unless current_user.has_role? 'admin'

答案 2 :(得分:2)

@available_option_types.delete_if do |ot|
  !ot.retailer.present? || current_user.retailer.id != ot.retailer.id
end unless current_user.has_role? 'admin'

@available_option_types.select do |ot|
  ot.retailer.present? && current_user.retailer.id == ot.retailer.id
end unless current_user.has_role? 'admin'

答案 3 :(得分:1)

如果零售商:has_many option_types

,这可能会有效
@available_option_types = current_user.retailer.options_types unless current_user.has_role? 'admin'