Created
May 27, 2015 22:41
-
-
Save janko/84dd3cd1c43d822dc07b to your computer and use it in GitHub Desktop.
Double dispatch in Ruby example (my presentation at a local Ruby meetup)
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
module SocialPresenter | |
# ... | |
class Twitter < Struct.new(:object) | |
def message | |
case object | |
when String | |
case object | |
when "/chart/artists" then t("Popular artists via %{twitter_tag}") | |
when "/chart/albums" then t("Popular albums via %{twitter_tag}") | |
when "/chart/tracks" then t("Popular tracks via %{twitter_tag}") | |
end | |
when Playlist | |
t "#NowPlaying %{playlist_title} on %{twitter_tag}", | |
playlist_title: object.name | |
when Post | |
t "%{post_title} on %{twitter_tag}", | |
post_title: object.title | |
when Genre | |
t "#NowPlaying %{genre_name} music on %{twitter_tag}", | |
genre_name: object.display_name | |
when Artist | |
t "#NowPlaying %{artist_name} music on %{twitter_tag}", | |
artist_name: object.name | |
when Album | |
t "#NowPlaying %{album_name} by %{artist_name} on %{twitter_tag}", | |
album_name: object.name, | |
artist_name: object.artist.name | |
end | |
end | |
private | |
def t(text, options = {}) | |
I18n.t text, **options, twitter_tag: "@Rhapsody" | |
end | |
end | |
# ... | |
end |
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
module SocialPresenter | |
# ... | |
class Twitter < Struct.new(:object) | |
def message | |
send("#{object.class}_message") | |
end | |
def String_message | |
case object | |
when "/chart/artists" then t("Popular artists via %{twitter_tag}") | |
when "/chart/albums" then t("Popular albums via %{twitter_tag}") | |
when "/chart/tracks" then t("Popular tracks via %{twitter_tag}") | |
end | |
end | |
def Playlist_message | |
t "#NowPlaying %{playlist_title} on %{twitter_tag}", | |
playlist_title: object.name | |
end | |
def Post_message | |
t "%{post_title} on %{twitter_tag}", | |
post_title: object.title | |
end | |
def Genre_message | |
t "#NowPlaying %{genre_name} music on %{twitter_tag}", | |
genre_name: object.display_name | |
end | |
def Artist_message | |
t "#NowPlaying %{artist_name} music on %{twitter_tag}", | |
artist_name: object.name | |
end | |
def Album_message | |
t "#NowPlaying %{album_name} by %{artist_name} on %{twitter_tag}", | |
album_name: object.name, | |
artist_name: object.artist.name | |
end | |
private | |
def t(text, options = {}) | |
I18n.t text, **options, twitter_tag: "@Rhapsody" | |
end | |
end | |
# ... | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment