ruby - Is there a way to dynamically add a scope to an active record class? -


i trying dynamically add scope active record object. of things have been trying via metaprogramming not working. below sort of want achieve.

class utilityclass    def add_scope_to_class klass, name, lambda      # should add      # scope :published, -> { where(published: true) }      code = lambda { filter_clause(value, &lambda) }      klass.class_exec(&code)    end end  class article < activerecord::base end  utilityclass.add_scope_to_class  article.published # returns published articles 

i have tried couple of variations of plain ruby objects, thought asking question context might different ideas/answers.

thanks.

updated

so far have managed come following it's not working

class activesearch   attr_accessor :collection   attr_reader :params    def initialize params={}     @params = params   end    def results     @collection = person.where(nil)     params.compact.each |key, value|       @collection = @collection.send("#{key}_filter", value)     end     @collection   end    def self.filter name, filter_proc     code = lambda { |filter_name| scope("#{filter_name.to_s}_filter".to_s, filter_proc) }     person.class_exec(name, &code)   end end  class personsearch < activesearch   filter :first_name, ->(name){ where(first_name: name) } end 

i have hard coded couple of things. main idea there.

after playing around, found solution bit simpler thought.

class activesearch   attr_accessor :collection   attr_reader :params    def initialize params={}     @params = params   end    def results     @collection = person.where(nil)     params.compact.each |key, value|       @collection = @collection.send("#{key}_filter", value)     end     @collection   end    def self.filter name, filter_proc     person.define_singleton_method "#{name.to_s}_filter".to_sym, &filter_proc # of heavy lifting   end end  class personsearch < activesearch   filter :first_name, lambda { |name| where(first_name: name) }   filter :last_name, lambda { |name| where(last_name: name) } end   personsearch.new({first_name: 'ryan', last_name: 'test'}).results 

the above combine appropriate methods , execute query.

a couple of tweaks needed, it's pretty doing want. active search class still needs cleaned , made generic, think gets idea across.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -