本文介绍了在Rails中确定两个(或多个)给定URL(作为字符串或哈希选项)是否相等的最佳方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个称为same_url的方法吗?如果传入的URL相等,则返回true。传入的URL可能是参数选项哈希或字符串。

I'm wanting a method called same_url? that will return true if the passed in URLs are equal. The passed in URLs might be either params options hash or strings.

same_url?({:controller => :foo, :action => :bar}, "http://www.example.com/foo/bar") # => true

Rails框架帮助器似乎是一个很好的起点,但我想传入任意数量的URL。

The Rails Framework helper current_page? seems like a good starting point but I'd like to pass in an arbitrary number of URLs.

作为额外的奖励如果可以传递要从比较中排除的参数散列,那就很好了。所以方法调用可能看起来像:

As an added bonus It would be good if a hash of params to exclude from the comparison could be passed in. So a method call might look like:

same_url?(projects_path(:page => 2), "projects?page=3", :excluding => :page) # => true 


推荐答案

这里是方法(在/ lib和在环境.rb中要求它):

Here's the method (bung it in /lib and require it in environment.rb):

def same_page?(a, b, params_to_exclude = {})
  if a.respond_to?(:except) && b.respond_to?(:except)
    url_for(a.except(params_to_exclude)) == url_for(b.except(params_to_exclude))
  else
    url_for(a) == url_for(b)
  end
end

如果您在Rails之前, 2.0.1 ,还需要将 except 辅助方法添加到哈希中:

If you are on Rails pre-2.0.1, you also need to add the except helper method to Hash:

class Hash
  # Usage { :a => 1, :b => 2, :c => 3}.except(:a) -> { :b => 2, :c => 3}
  def except(*keys)
    self.reject { |k,v|
      keys.include? k.to_sym
    }
  end
end

Rails(好吧,ActiveSupport)已经包括,除了(信誉:)

Later version of Rails (well, ActiveSupport) include except already (credit: Brian Guthrie)

这篇关于在Rails中确定两个(或多个)给定URL(作为字符串或哈希选项)是否相等的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-30 18:04