We all know Ruby supports functional style programming: it’s got blocks! But it’s still, at bottom, an object-oriented language. What are some ways we can combine OO and FP to good effect?
follow_criteria.call(tweeter) follow!(tweeter) end end end end twitter_bot_builder.follow_tweeter_if do |tweeter| tweeter.recent_tweets(50).grep(/rubynation/) end
unless emails.include?(watcher.email) IssueMailer.tell_watch_area(watch_area, issue).deliver emails << watcher.email end end Recommendation.for(issue).each do |user| unless emails.include?(user.email) IssueMailer.recommend(user, issue).deliver emails << user.email end end
mail.guard(watcher.email) do IssueMailer.tell_watch_area(watch_area, issue).deliver end end Recommendation.for(issue).each do |user| mail.guard(user.email) do IssueMailer.recommend(user, issue).deliver end end
|watch_area| mail.guard(watcher.email, :tell_watcher) do IssueMailer.tell_watch_area(watch_area, issue).deliver end end Recommendation.for(issue).each do |user| mail.guard(user.email, :recommend) IssueMailer.recommend(user, issue).deliver end end
• Separate API interaction: pass a function to handle the data • Separate the actions from deciding whether to take them: pass them as functions s e p a r a t e
class MethodFromFunction define_method(:double, ->(x) { x * 2 }) end class MethodFromFunctionVariable double = ->(x) { x * 2 } define_method(:double, double) end
up dood?’ # add bang, prepend ‘vote for’, yell it class Yeller def oy(name) [‘oy,’, name].join(‘ ‘).upcase end def wat_up(name) [“#{name}!”, ‘wat up dood?’].join(‘ ‘) end def vote_for(name) [‘vote for’, “#{name}!”].join(‘ ‘).upcase end end