我知道如何检查lambda的arity(函数参数个数),但我不知道如何从作用域中提取它。
这个问题是4年前提出的:
https://groups.google.com/forum/#!topic/rubyonrails-core/7Cs0T34mj8c
All, In the course of working on a change for the meta-search gem I've run into an issue with the way that scopes are implemented in ActiveRecord. In order to include a scope in a search we pass the name of the scope to a search method like so:
{:name_of_my_scope => 1}
. Meta-search automatically passes the"1"
as an argument to the scope. This causes anArgumentError
with lambda scopes that don't take an argument.My intention was to check the arity of the scope before calling and dropping the
"1"
in the event the scope didn't take an argument. My issue is that the implementation of scope wraps scope_options up in a lambda that passes *args to the block (active_record/named_scope.rb: 106). This results in the call to arity always returning -1 regardless of the actual number of arguments required by the scope definition.Is there a different way to implement scopes that would allow exposing the arity from the scope definition?
Ex.
class Post < ActiveRecord::Base scope :today, lambda {where(:created_at => (Time.new.beginning_of_day...(Time.new.end_of_day)) } end irb> Post.today.arity # => -1
在调用作用域之前,它要求帮助查找其数量。
已经找到解决方案了吗?