简体   繁体   中英

rails organizing folders for service objects

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM