Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically generate scopes in rails models

I'd like to generate scopes dynamically. Let's say I have the following model:

class Product < ActiveRecord::Base
    POSSIBLE_SIZES = [:small, :medium, :large]
    scope :small, where(size: :small) 
    scope :medium, where(size: :medium) 
    scope :large, where(size: :large) 
end

Can we replace the scope calls with something based on the POSSIBLE_SIZES constant? I think I'm violating DRY to repeat them.

like image 404
spike Avatar asked Dec 27 '12 21:12

spike


2 Answers

you could do

class Product < ActiveRecord::Base
  [:small, :medium, :large].each do |s|
    scope s, where(size: s) 
  end
end

but I personally prefer:

class Product < ActiveRecord::Base
  scope :sized, lambda{|size| where(size: size)}
end
like image 167
Cristian Bica Avatar answered Sep 22 '22 17:09

Cristian Bica


you can do a loop

class Product < ActiveRecord::Base
    POSSIBLE_SIZES = [:small, :medium, :large]
    POSSIBLE_SIZES.each do |size|
        scope size, where(size: size)
    end
end
like image 30
Lluís Avatar answered Sep 18 '22 17:09

Lluís