How to return something from a Concern and update a record?

211 views Asked by At

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) }
1

There are 1 answers

0
mcfoton On

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 ConcernName you're adding class and/or instance methods on the model class/instance itself. So your create_sort_title method that is called from before_save callback will have access to all instance methods, including title and will work as-is just fine