【问题标题】:Where do I place a file that exntends the hash class in Rails?我在哪里放置扩展 Rails 中的哈希类的文件?
【发布时间】:2016-10-14 21:17:49
【问题描述】:

我使用的是 Rails 4.2.7.1。我想创建一个不区分大小写的哈希,如此处所述 — How do I create a hash in Ruby that compares strings, ignoring case? 。我创建了文件 app/active-support/hash_with_indifferent_access.rb,使用

class CaseInsensitiveHash < HashWithIndifferentAccess
  # This method shouldn't need an override, but my tests say otherwise.
  def [](key)
    super convert_key(key)
  end

  protected

  def convert_key(key)
    key.respond_to?(:downcase) ? key.downcase : key
  end  
end

但是当我加载我的控制台时,它无法识别哈希……

davea$ rails console
Loading development environment (Rails 4.2.7.1)
2.3.0 :001 > h = CaseInsensitiveHash.new
NameError: uninitialized constant CaseInsensitiveHash
    from (irb):1
    from /Users/davea/.rvm/gems/ruby-2.3.0/gems/railties-4.2.7.1/lib/rails/commands/console.rb:110:in `start'
    from /Users/davea/.rvm/gems/ruby-2.3.0/gems/railties-4.2.7.1/lib/rails/commands/console.rb:9:in `start'
    from /Users/davea/.rvm/gems/ruby-2.3.0/gems/railties-4.2.7.1/lib/rails/commands/commands_tasks.rb:68:in `console'
    from /Users/davea/.rvm/gems/ruby-2.3.0/gems/railties-4.2.7.1/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
    from /Users/davea/.rvm/gems/ruby-2.3.0/gems/railties-4.2.7.1/lib/rails/commands.rb:17:in `<top (required)>'
    from bin/rails:4:in `require'
    from bin/rails:4:in `<main>'

我应该将我的文件放在哪里,以便在我的项目中获取它?

【问题讨论】:

  • config/initializers/是最常用的地方

标签: ruby-on-rails class hash helper


【解决方案1】:

我通常把这些东西放在 lib/core_ext/hash.rb 中。但这取决于你。我所做的你缺少的是创建一个 config/initializers/require.rb 文件,如下所示:

require "core_ext/hash"
require "core_ext/array"
...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-25
    • 1970-01-01
    • 1970-01-01
    • 2011-03-22
    • 2011-01-13
    • 2014-11-06
    • 2013-03-29
    • 1970-01-01
    相关资源
    最近更新 更多