views:

541

answers:

2

Hi,

following example:

named_scope :search, lambda {|my_args| {...}} do
  def access_my_args
    p "#{my_args}"
  end
end

# Call:
Model.search(args).access_my_args

As you can see I want to access the arguments from the lambda in the named_scope extension. Is there a way to do this?

A more specific example:

class User < ActiveRecord::Base
  named_scope :by_name, lambda {|name_from_scope| {:conditions => {:name => name_from_scope}}} do
    def change_name
     each { |i| i.update_attribute(:name, "#{name_from_scope}xyz") }
    end
  end
end

(I know that there is a find_by_name scope and so on...). I want to use the name_from_scope argument, that is passed in the scope in the scope extension.

A: 

Is this what you're trying to do?

named_scope :search, lambda {|*my_args|
    OtherClass.announce_search_for_model(my_args, self.class)
    { :conditions => ['created_at < ?', my_args[:created_at]], :limit => my_args[:limit] }
}

args = {:created_at > 'NOW()', :limit => 5}
Model.search(args)

If you're wanting to observe what's passed onto the named_scope then I would do that in the lambda.

Named_scope results will always be a result as if you'd used Model.find. This is a functionality of rails so you need to override rails functionality with a Module if you want something different. I wouldn't recommend doing that because named_scope extensions are there for simplifying finders, not observing parameters.

nessence
the new example should make it clearer
Stevens
Thanks. I posted an additional answer. I posted a second answer as clarification my first isn't what you were trying to accomplish :)
nessence
+1  A: 
named_scope :test_scope, lambda {|id| {:conditions => {:id => id}} } do
    def test_scope_method
      each {|i| puts @proxy_options.to_yaml}
    end
  end

I don't believe you can get to the arguments directly without extending activerecord.

@proxy_options will give you the compiled options in the block. So, in your example, you won't have access to name_from_scope but you will have access to @proxy_options[:conditions][:name].

nessence
well it works, but its still kind of a hack ;)
Stevens
and you have to parse it if you are not using a hash as condition
Stevens