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.

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

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

For rails 4+, just updating @bcd 's answer

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

or

class Product < ActiveRecord::Base
  scope :sized, ->(size) { where(size: size) }
end

Need Your Help

White balance algorithm

algorithm image-processing image-enhancement

I'm doing some image processing and I need an automatic white balancing algorithm that's not too intensive in terms of CPU computation time. Any recommendations?

(Why) do we need to call cache or persist on a RDD

scala apache-spark rdd

When a resilient distributed dataset (RDD) is created from a text file or collection (or from another RDD), do we need to call "cache" or "persist" explicitly to store the RDD data into memory? Or ...