Created
April 5, 2015 05:51
-
-
Save coreyhaines/f4bc2b903dfe0dee4069 to your computer and use it in GitHub Desktop.
The boss of metaprogramming
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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!!!! |
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
I don't understand what lines 2-11 do. I'm glad you ameliorated it.