Skip to content

Instantly share code, notes, and snippets.

@coreyhaines
Created April 5, 2015 05:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save coreyhaines/f4bc2b903dfe0dee4069 to your computer and use it in GitHub Desktop.
Save coreyhaines/f4bc2b903dfe0dee4069 to your computer and use it in GitHub Desktop.
The boss of metaprogramming
# You know you are the boss, when you take this
def filter(questions_query)
filter_categories filter_incomplete questions_query
end
def filter_incomplete(query)
filtering_on?(:incomplete) ? query.incomplete : query
end
def filter_categories(query)
filtering_on?(:categories) ? query.in_categories(*@original_params[:categories]) : query
end
# and make it so much more glorious with amazing metaprogramming skillz to eliminate all that horrible duplication
def self.generate_filter(key, if_filtering)
define_method "filter_#{key}" do |query|
filtering_on?(key) ? if_filtering.(query, @original_params) : query
end
end
filters = {
:incomplete => ->(query, original_params) { query.incomplete },
:categories => ->(query, original_params) { query.in_categories(*original_params[:categories]) }
}
filters.each_pair do |key, filter|
generate_filter key, filter
end
class_eval <<LOL
def filter(questions_query)
#{filters.keys.map{|f| "filter_#{f}"}.join(" ")} questions_query
end
LOL
# Now I can add new filters by adding the filter hash! AMAZEBALLS! NO MORE DUPLICATION!!!!
@chad
Copy link

chad commented Apr 5, 2015

I don't understand what lines 2-11 do. I'm glad you ameliorated it.

@coreyhaines
Copy link
Author

I know, right. I'm a firm believer in intention-revealing coding, as well as eliminating duplication. It is a fine line, but my many years of programming help me navigate that line. Clearly the second form solves a lot of the readability problems of the first form.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment