0

您可以在github.com/ddd1600/simple_angel查看文件结构中的所有内容

我在尝试“正确的方式”创建一个 ruby​​ 应用程序(很快成为一个 gem)时遇到了很多错误,即。通过将逻辑彻底划分为类和“加载器文件”等等。关键是,我知道如何以更简单的方式编写此代码,而不遵守 OO 原则,但我想“正确”地做。

所以,首先,文件结构如下——

root folder = ~/Develop/simple_angel

inside /simple_angel
  - /lib
  - Gemfile
  - Rakefile
  - simple_angel.gemspec

inside /lib
  - simple_angel.rb
  - /simple_angel

inside /lib/simple_angel
  - company.rb
  - search.rb
  - version.rb

但是,这里有一些基础知识。

这是我从终端运行这个程序所调用的(运行时的路径是 ~/Develop/simple_angel)

ruby -Ilib lib/simple_angel/search.rb

这是search.rb

#these 'requires' are supposed to be loaded in lib/simple_angel.rb, so here I show
#them commented out
#
#require 'rubygems'
#require 'httparty'
#require 'json'
#require 'company'

module SimpleAngel
  class Search

  SEARCH_URL = "http://api.angel.co/1/startups"

  def search(user_input)

    response = HTTParty.get("#{SEARCH_URL}/#{user_input}")
    parsed_response = JSON.parse(response.body)

    Company.new(parsed_response)

  end
 end  

 s = SimpleAngel::Search.new
 s = Search.new
 x = s.search(6702)
 p x
 end

这是“加载器”文件,lib/simple_angel.rb(PS:这种文件的更正式的标题是什么?)

require 'httparty'
require 'json'
require 'simple_angel/search'
require 'simple_angel/version'
require 'simple_angel/company'

module SimpleAngel

end

最后,当我(再次)运行“ruby -Ilib lib/simple_angel/search.rb”时(所有 search.rb 的 'requires' 都被注释掉了 (^&^),这是我的错误消息:

[ddouglas@coders:~/Develop/simple_angel on master]
% ruby -Ilib lib/simple_angel/search.rb                                       
lib/simple_angel/search.rb:15:in `search': uninitialized constant SimpleAngel::Search::HTTParty (NameError)
from lib/simple_angel/search.rb:24:in `<module:SimpleAngel>'
from lib/simple_angel/search.rb:8:in `<main>'

^&^ - 既然我们都在这里加快速度,我不妨包括当我离开 search.rb 的“要求”时发生的错误

% ruby -Ilib lib/simple_angel/search.rb                                       ✹
/usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require': cannot load such file -- company (LoadError)
from /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
from lib/simple_angel/search.rb:6:in `<main>'
4

2 回答 2

1

我不能说我理解班级试图提出的关于拆分文件的观点。

第一个错误 ( uninitialized constant SimpleAngel::Search::HTTParty) 是因为SimpleAngel::Search您从内部调用HTTParty. 尝试将其更改::HTTParty为指定根命名空间。

于 2012-07-11T01:27:39.303 回答
0

回顾这个问题,大局问题是我可能只需要通过添加到 config/application.rb 来激活 rails 中的 /lib 文件夹

config.autoload_paths += Dir["#{config.root}/lib/**/"]

从那里,代码可以通过file_name.rb => FileName类系统从rails中的任何地方直接加载

于 2013-04-04T03:57:58.450 回答