Skip to content

Instantly share code, notes, and snippets.

@dcluna
Created March 22, 2012 17:29
Show Gist options
  • Select an option

  • Save dcluna/2160375 to your computer and use it in GitHub Desktop.

Select an option

Save dcluna/2160375 to your computer and use it in GitHub Desktop.
Metaprog: dynamically add methods to a class
module DateFilterable
private
def filterable_by(field)
class_filter = %Q{def filter_by_date(min,max=nil)
if max.nil?
where("#{field} > :min_date", { :min_date => min } )
else
where("#{field} >= :min_date, #{field} < :max_date", { :min_date => min, :max_date => max } )
end
end}
field_date_accessor = %Q{def #{field}
Date.new(Integer read_attribute(:#{field}))
end}
instance_eval class_filter
class_eval field_date_accessor
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment