I want to move some class methods for some of my models that are the same to a concern. One method takes an input and returns something which then should be used to update a record like this:
def create_sort_title
self.sort_title = self.title.gsub(/^the |^a |^an /i, '').gsub(/'|"|!|\?|-/, '').gsub(/(?<!\w) /,'')
end
While it's clear that I need to refactor it to take an input:
def create_sort_title(title)
self.sort_title = title.gsub...
...
I don't understand how I can RETURN a value to update a record - i. e. how to replace the self.sort_title above with something that then is used to update the sort_title of the corresponding record?
The method is called by a before_safe hook:
before_save :create_sort_title
(and I understand once I take an argument, I need to use a lambda like this:
before_save -> { create_sort_title(title) }
You don't really need to pass any arguments if you're using a concern that is included on the model. When you do
include ConcernNameyou're adding class and/or instance methods on the model class/instance itself. So yourcreate_sort_titlemethod that is called frombefore_savecallback will have access to all instance methods, includingtitleand will work as-is just fine