ActiveRecord named_scope, .scopes

The background to this problem is rather complicated and confusing, and since I am looking for a simple answer, I will leave it on the sidelines explaining my problem, and instead provide this hypothetical situation.

If I have a simple ActiveRecord model called Automobile, with named_scopes, as shown below:

named_scope :classic, :conditions => { :build_date <= 1969 }
named_scope :fast, lambda { |speed| :top_speed >= speed }

Ignoring the areas themselves if I were to call:

Automobile.scopes

What exactly will this return? What I see in the console:

[ :classic => #<Proc:0x01a543d4@/Users/user_name/.gem/ruby/1.8/gems/activerecord-2.3.4/lib/active_record/named_scope.rb:87>,
  :fast => #<Proc:0x01a543d4@/Users/user_name/.gem/ruby/1.8/gems/activerecord-2.3.4/lib/active_record/named_scope.rb:87> ]

It seems to me that this is an array of keys / values, the key is a symbol of the named area, and the value is Proc, pointing to the named_scope.rb file in ActiveRecord.

If I want a hash or Proc to be specified as the actual namespace (value for: classic, I would get ": conditions => {: build_date <= 1969}", how could I find this?

, named_scopes, . :

scopes_to_use = Automobile.scopes
scoped_options = {}
Automobile.scopes.each do |scope|
    scoped_options.safe_merge!(eval "Automobile.#{scope}(self).proxy_options")
end

"" , , , Hash Proc named_scope? "eval" , Hash Proc, . . .

+3
1

, , . . , .

, , . .

Proc, .

Model.scopes[:scope_name] proc. Model.send(:scope_name).proxy_options -, , : { :conditions => ["build_date <= ?", 1969] }

, :

scopes_to_use = Automobile.scopes
scoped_options = {}
Automobile.scopes.keys.each do |scope|
    scoped_options.safe_merge!(Automobile.send(scope).proxy_options)
end

, , . , .

, , proc, , , . , arity - -2. , arity, proc, . .

eval. - proxy_options .

- , , :

scopes_to_use = Automobile.scopes
    scoped_options = {}
Automobile.scopes.each do |scope,proc|
  next if scope == :scoped
  number_of_args = 1
  begin
    scoped_options.safe_merge! Automobile.send(scope, "#{scope}_argument_1").proxy_options
  rescue 
    $!.to_s.match /(\d+)\)$/
    number_of_args = $1.to_i
    puts number_of_args
  end
     scoped_options.safe_merge!(Automobile.send(scope, *(1..number_of_args).map{|i| "#{scope}_argument_#{i}"}.proxy_options)
end

, proxy_options SQL .

+2

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


All Articles