You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
If I need to get a value, I would just grab it from the hash in the normal way
album_name=album[:album_name]# >> Pure Heroine (Deluxe)
If I needed to do something to the album
like extract 'Deluxe' from the album_name and set a flag
I would create a method
defnormalize(album)ifalbum[:album_name].end_with?(" (Deluxe)")# update album_name to be name without " (Deluxe)"# set new k/v of album[:deluxe] = trueendreturnalbumendnormalized_album=normalize(album)normalized_album[:album_name]# >> Pure Heroinenormlized_album[:deluxe]# >> true
Often I'd need to grab the artist name and album to use as a search phrase
search_keywords="#{album[:artist_name]}#{album[:album_name]}"# >> "Lorde Pure Heroine"
Doing this is perfectly fine
But sometimes I would create an album using the wrong key value
eg. 'album:' instead of 'album_name'
This would break the methods eg. normalize
Also, it started to become annoying to keep wrapping the album hash in methods that you had to put in front of it ie. normalize(album)
I started thinking if there was a better way
ideally, you want to take the album and then do something to it. Maybe... album.normalize
So I created an Album class
This standardises what value types the object can have ie. will error imediately if I try and create using 'album' instead of 'album_name'
The real benefit comes with the methods that I can include in the class
eg
classAlbumincludeActiveModel::Modelattr_accessor:release_name,:artist_name,:url,:site,:tracks,:price,:deluxe,:explicitness,:cover,:id,:artist_iddefinitialize(release_name,artist_name,url,site)@release_name=release_name@artist_name=artist_name@url=url@site=siteenddefnormalizeifself.album_name.end_with?(" (Deluxe)")# update album_name to be name without " (Deluxe)"# set new k/v of album[:deluxe] = trueendreturnalbumenddefartist_release_keywords"#{self.artist_name}#{self.album_name}"endprivate# add methods here that the other methods above might use# keeps the main methods clean and readable# while keeping all relevant stuff togetherendalbum.normalize# >> # album_name: "Pure Heroine"# artist_name: "Lorde"# url: "https://music.apple.com/gb/album/pure-heroine/1440818584?uo=4&at%0D=1010lxMt%0D"# site: :itunes# deluxe: truealbum.artist_release_keywords# >> Lorde Pure Heroine
You can also now easily add validation
eg. ensure that 'tracks' is an integer
Because I scrape some results from html, they return as String and I usually forget to convert them which produces errors in other code I use
You could detect errors early with class validation