Amol Pujari
Amol Pujari

Reputation: 2347

define a scope at run time

I have models Gateway and GatewayType, and I am looking for

Gateway.<gateway_type.name> # => Gateway.where(:gateway_type_id => gateway_type.id) 

Now this <gateway_type.name> scope should get created at run time, similar to adding class/instance level methods at run time using defined_method like below

class Object
  def metaclass
    class << self
      self
    end
  end
end

# adding class level methods
GatewayType.all.each do |type|
  # adding methods to Gateway
  Gateway.metaclass.class_eval do
    define_method "all_#{type.name}" do
      Gateway.where(:gateway_type_id => type.id)
    end
  end
end

I do not want to go with above approach, as it wont allow me to add all_xyzs in between where or other scope like

Gateway.scope1.all_xyzs.scope2

So... is there any way to have scope defined at runtime?

Upvotes: 1

Views: 233

Answers (2)

Amol Pujari
Amol Pujari

Reputation: 2347

After trying out a lot of 'eval' and other stuff I got the following working just replacing above defined method as

  define_method "#{type.name}" do
    where(:gateway_type_id => type.id)
  end

and its working as per I want Gateway.scope1.xyzs.scope2

Upvotes: 0

Ryan Bigg
Ryan Bigg

Reputation: 107728

If you want all Gateway objects for a particular GatewayType, why not do this?

gateway_type = GatewayType.find(id)
gateway_type.gateways

I assume in this case that you have has_many :gateways on GatewayType. The association methods in Rails would allow you to restrict queries to a subset of gateways for a particular GatewayType object.

Upvotes: 1

Related Questions