1

I make a script to try some functions. But I cannot use models in lib. Interesting is, that I already have an lib, and there it works fine with the mostly same code(?).

// script/tags.rb:
require File.expand_path('../../config/application',  __FILE__)
require 'company_tags'

host = ARGV[0] || 'team1.crm.tld'

c = CompanyTags.new(host)
c.run

// lib/company_tags.rb
class CompanyTags 
  def initialize(host)
    @site = Site.where(host: host).first
  end

  def run
    comp = @site.companies.first
    comp.tag_list.add("tag1")
    comp.general_list.add("tag_general")
    comp.save!
    p comp.tag_list
  end
end

Error: /lib/company_tags.rb:3:in `initialize': uninitialized constant CompanyTags::Site (NameError)

TheVic
  • 303
  • 6
  • 16

4 Answers4

3

You need to require the environment, not the application.

require File.expand_path('../../config/environment',  __FILE__)
require 'company_tags'

The environment will load all the dependencies, including the application, and it will bootstrap the application.

Simone Carletti
  • 173,507
  • 49
  • 363
  • 364
  • Wow. Thank you, it works very well. But, you can explain me, why the same code work for another pairs of script+lib? There i used application. – TheVic Oct 30 '14 at 18:27
  • 1
    It may have worked because it was loaded in a different way, for example via console. Or because you are not using models defined in the environment. – Simone Carletti Oct 30 '14 at 19:36
2

Just an idea, but try changing Site.where(host: host).first to ::Site.where(host: host).first. Putting the :: in front, causes ruby to look for Site in the global namespace instead of as a constant defined in CompanyTags.

jerhinesmith
  • 15,214
  • 17
  • 62
  • 89
1

You can add a simple configuration to config/application.rb:

# Autoload lib/ folder including all subdirectories
config.autoload_paths += Dir["#{config.root}/lib/**/"]

Check this question out for more details.

Community
  • 1
  • 1
mohameddiaa27
  • 3,587
  • 1
  • 16
  • 23
1

In my previous answer, I thought you were running rails console. Your main issue is that the Site class is not required. Here is how requiring files to your classes work.

Through the require_all function

require_all(MY_CLASSES_DIRECTORY)

Or by requiring each class manually:

require 'Class_NAME.rb'

Notice that the Site class is not required anywhere.

For more details, check this link

mohameddiaa27
  • 3,587
  • 1
  • 16
  • 23