0

I want to include the following class from my services folder into my Controller..

Here is the Class in ..services/product_service.rb

class MyServices
 class << self
  def screen_print
   "These are the words in screen print"
  end
 end
end

And all I want to do is this in my controller:

class AmazonsController < ApplicationController
 def index
  @joe = MyServices.screen_print
 end
end

I thought I could just include it in the controller. And its not a module so include isn't working, and I tried updating my config/appliaction.rb file and that didn't work either..

user229044
  • 232,980
  • 40
  • 330
  • 338
ToddT
  • 3,084
  • 4
  • 39
  • 83

3 Answers3

2

Your class name needs to be the same as the name of your file, I believe. So since your file is named product_service.rb, your class should be:

class ProductService
  class << self
    def screen_print
      "These are the words in screen print"
    end
  end
end

and in your controller:

class AmazonsController < ApplicationController
  def index
    @joe = ProductService.screen_print
  end
end
Danny Y
  • 261
  • 3
  • 9
  • Booyah!! Thanks so much Danny.. I thought there was some Ruby magic in there somewhere, and that was it.. thanks much! I'll accept this answer when I can.. – ToddT Dec 23 '15 at 15:29
  • No problemo :) The answer that @meagar posted is also worth a read if you aren't with Rails autoloading. Anything under your "app" directory should get autoloaded by Rails by default, but if you were to add anything in say, your 'lib" folder, or a new folder in your root path, you'd have to autoload the paths. – Danny Y Dec 23 '15 at 15:37
1

In addition to the naming problems already pointed out, Rails won't automatically require arbitrary files from folders it doesn't know about.

If you want files in a new folder to be automatically required, you need to add it to Rails' autoload paths:

# config/application.rb
config.autoload_paths << Rails.root.join('services')

See Auto-loading lib files in Rails 4 for more details.

Community
  • 1
  • 1
user229044
  • 232,980
  • 40
  • 330
  • 338
  • http://edgeguides.rubyonrails.org/autoloading_and_reloading_constants.html#autoload-paths all subdirectories under `app/` will be autoloaded if I understand correctly – Laurens Dec 23 '15 at 15:34
  • @Laurens There is no indication that `services` is in `app`. He simply says "from ..services/product_service.rb", whatever that means. – user229044 Dec 23 '15 at 15:35
0

Rails does not load files from uncommon locations. You will need to tells Rails that the services folder exists and to load file from it.

Add the following to your config/application.rb:

# Custom directories with classes and modules you want to be autoloadable.
config.autoload_paths += [Rails.root.join('app', 'services')]
spickermann
  • 100,941
  • 9
  • 101
  • 131