ruby-extend-vs-include
Yesterday there was a lot of bugnags after our last builds on production. Initially we thought they came after powr-v2 app that we deployed on Friday, but turning off all dynos of powr-v2 didn’t help, and me and Ali started digging into a solution. We found out, that if you wrote module as usual and then include that in Class then it will include PowrUrls module as an instance properties but functions of PowrUrls aren’t going to become Class functions.
module PowrUrls
def base_url
case Rails.env
when 'development';
ENV['NGROK_URL'] || 'https://localhost:3000'
when 'staging';
ENV['BASE_URL'] || 'https://www.powr-staging.io'
when 'production';
'https://www.powr.io'
end
end
This code is not going to work for a lot of implications, because of the way include works on Ruby, to solve it you might need extend operator. Think it’s a good learning point, the difference between include and extend in ruby, here’s an article that helped us to undertand it. For some modules, like a Sidekiq or Worker you might need doing both include and extend in one file, and considering that we needed that for multiple places we end up rewriting PowrUrls so that it describes ClassMethods along with instance methods:
module PowrUrls
def self.included(base)
base.extend(ClassMethods)
end
module ClassMethods
def base_url
case Rails.env
when 'development';
ENV['NGROK_URL'] || 'https://localhost:3000'
when 'staging';
ENV['BASE_URL'] || 'https://www.powr-staging.io'
when 'production';
'https://www.powr.io'
end
end
end
def base_url
case Rails.env
when 'development';
ENV['NGROK_URL'] || 'https://localhost:3000'
when 'staging';
ENV['BASE_URL'] || 'https://www.powr-staging.io'
when 'production';
'https://www.powr.io'
end
end
It solved all the bugsnags and fixed the issue.