Arity Scopes in Rails 4

I know how to check arity lambda, but I don't know how I can extract it from the area.

This question was asked 4 years ago:

https://groups.google.com/forum/#!topic/rubyonrails-core/7Cs0T34mj8c

That's it. While working on changing the meta-distortion, I ran into a problem related to the way ActiveRecord. To enable the area in search, we pass the name of the scope of the search method: {:name_of_my_scope => 1}. A meta search automatically passes "1"as an argument to the area. This calls ArgumentErrorwith lambda regions that take no argument.

My intention was to verify the reality of the area before calling and discarding "1"if the area did not accept the argument. my problem is that the scope implementation wraps scope_options in lambda, which passes * args to the block (active_record / named_scope.rb: 106). This results in an arity call, always returning -1 regardless of the actual number of arguments required by the scope definition.

Is there any other way to implement areas that will expose due to the definition of the scope?

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

He asks for help in finding the visibility of the scope before calling it.

Was a solution found?

+4
source share
1 answer

scope,

irb(main):070:0> User.method(:active_users).parameters
=> [[:rest, :args]]

:rest , . .

, , , ArgumentError - :

ArgumentError: wrong number of arguments (1 for 2)

ArgumentError, arity, arity .

, hack, , , , -.

Model, scope , 100 , , , ArgumentError - .

:

def self.scope_arity scope_symbol
    begin
        send(scope_symbol, (1..100).to_a) 
    rescue ArgumentError => e
        f = e.message.scan(/for\s+(\d+)/).flatten.first
        f.to_i.nonzero? || 0
    end
end

:

irb(main):074:0> User.scope_arity(:active_users)
=> 2
+1

Source: https://habr.com/ru/post/1620187/


All Articles