Last active
September 17, 2020 10:29
-
-
Save miatrinity/3ed36b1719ee33775ca2bdb29369c578 to your computer and use it in GitHub Desktop.
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
# original code | |
# we have an array of strings | |
# | |
# we want to build a HTML list, where each string is wrapped in a <li> tag | |
# <li>s are separated by <hr>s | |
# | |
# conventional way: build the result string piece by piece: | |
# | |
# starting with the opening <ul> tag | |
# looping over the strings and adding the <li>s, and a <hr> UNLESS we are dealing with the last <li> | |
# finally, closing the <ul> tag | |
def apps_list | |
apps = App.where.not(name: @current_app.name).all_valid.pluck(:name) | |
ul_content = "<ul class='list-unstyled list-popover apps-selector'>" | |
apps.each_with_index do |app, index| | |
ul_content += wrap_with_li app | |
ul_content += '<hr>' unless last_item?(index, apps.size) | |
end | |
ul_content + '</ul>' | |
end | |
# refactored code | |
# using Array#map to wrap `app`s in <li> tags | |
# then joining the <li> tags with <hr> | |
# finally tossing the above result into an <ul> sandwich | |
def apps_list | |
apps = App.where.not(name: @current_app.name).all_valid.pluck(:name) | |
list_items = apps.map { |app| wrap_with_li app }.join('<hr>') | |
<<-LIST | |
<ul class='list-unstyled list-popover apps-selector'> | |
#{list_items} | |
</ul> | |
LIST | |
end | |
# drop temporary variable | |
# even though shorter, it's a bit too code golf-y 💻🏌⛳️ for my tastes | |
# I think explicitly naming list_items is worth the extra clarity | |
# so I slightly prefer the first pass, although this is not too bad either | |
def apps_list | |
apps = App.where.not(name: @current_app.name).all_valid.pluck(:name) | |
<<-LIST | |
<ul class='list-unstyled list-popover apps-selector'> | |
#{ apps.map { |app| wrap_with_li app }.join('<hr>') } | |
</ul> | |
LIST | |
end | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment