0

I'm trying yo create a service object to extract a few methods from the product.rb AR model, but for some reason I can't autoload the new TwitterShare class. When I hit up the console and try something like Product.last.twitter_share_text I get NameError: uninitialized constant Product::TwitterShare error.

What's going on in here? How should I organize my folders/files? Do I have to tell rails to autoload services? Here is the current code:

app/models/product.rb

class Product < ActiveRecord::Base  

  def twitter_share_text
    TwitterShare.new(name: self.name, oneliner: self.oneliner).return_text
  end

app/services/twitter_share.rb

class TwitterShare
  attr_reader .........

  def initialize....
end
Sean Magyar
  • 2,360
  • 1
  • 25
  • 57

1 Answers1

2

You need to let rails know where it could possibly find TwitterShare.

Add the following to your application.rb

config.autoload_paths << "#{Rails.root}/app/services"

and then restart the console or server.

rails should now be able to locate twitter_share.rb and load TwitterShare correctly.

Refer to Autoloading and Reloading Constants for more info.

Dharam Gollapudi
  • 6,328
  • 2
  • 34
  • 42
  • Thanks Dharam. I wasn't sure if this was the right way. I checked out a github repo where the guy is using the same folder structure but he didn't include this line in the `application.rb`. Thanks to that I thought there must be a better way to do it. – Sean Magyar Jun 08 '16 at 23:02