Question

Im trying to create an before_save callback for certain models that will add links and formatting to text and that gets saved in a special field. It won't let me include the URL helpers in the callback.

Here's my code:

module SocialText
  extend ActiveSupport::Concern

  included do
    before_save :action_before_save
  end

  def action_before_save
    self.body_formatted = htmlizeBody(self.body)
  end

  def htmlizeBody(body)
    include Rails.application.routes.url_helpers
    include ActionView::Helpers

    #replace all \ns with <br>
    body = body.gsub(/\n/, ' <br/> ')

    words = body.split(/\s/)
    words.map! do |word|
      if word.first == '@'
        username = extractUsernameFromAtSyntax word
        user = User.find_by! username: username

        if not user.nil?
          link_to(word, profile_path(user.username))
        else
          word
        end
      else
        word
      end
    end

    words.join " "
  end

  def extractUsernameFromAtSyntax(username)
    matchData = username.match(/@(\w+)(['.,]\w*)?/)

    if not matchData.nil?
      matchData[1]
    else
      username
    end
  end
end

I'm getting:

NoMethodError (undefined method `include`)

How do I get the helper? is there a better way to do this?

Was it helpful?

Solution

In your htmlizeBody function: include Rails.application.routes.url_helpers include ActionView::Helpers

This is in the wrong scope, moving it underneath extend ActiveSupport::Concern will resolve your error.

Another question you could ask yourself is why you need to use view helpers at the concern level?

include Rails.application.routes.url_helpers is usually used when modifying the default url host options (typically when you need to interface with an external API). In this case, it would make sense to use it in the /lib directory.

See this SO post and this post on using url helpers for more info

OTHER TIPS

include operates on a class instance object and you call it like an instance method.

You should take that include part outside of your methods.

Consider using require at your module scope.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top