Rails创建了一个可通过模型和控制器访问的方法

时间:2014-02-27 17:43:41

标签: ruby-on-rails ruby

无论如何要创建一个我可以在模型和控制器中调用的函数吗?我有一个函数,它抓取一个文件数组并剥离扩展,并希望对列表进行验证。但是我也希望在控制器中访问这个列表,这样我就可以为选项输出一个选择框。我目前有这个,但VALID_MODULES并没有一直填充。

class Job < ActiveRecord::Base

  after_initialize :init
  VALID_MODULES =[];

  validates :name, presence: true
  validates :desc, presence: true
  validates :api, presence: true, :inclusion => { :in => VALID_MODULES}
  validates :filters, presence: true
  validates :toe, presence: true

  def init
    Dir.foreach('lib/resources') do |item|
         next if item == '.' or item == '..' or item == 'resource.rb'
            #Wont be called very often so O(n) complexity is fine (small #elements)
            VALID_MODULES.push(item[0..-4]) unless VALID_MODULES.include?(item[0..-4])
    end
  end

end

2 个答案:

答案 0 :(得分:1)

请尝试将其设为VALID_MODULES的属性,而不是使用常量(job)。

class Job < ActiveRecord::Base

  attr_accessor :valid_modules
  after_initialize :init


  validates :name, presence: true
  validates :desc, presence: true
  validates :api, presence: true, :inclusion => { :in => VALID_MODULES}
  validates :filters, presence: true
  validates :toe, presence: true

  def init
    @valid_modules ||= []
    Dir.foreach('lib/resources') do |item|
         next if ['.', '..', 'resource.rb'].include?(item)
         #Wont be called very often so O(n) complexity is fine (small #elements)
         @valid_modules << item[0..-4] unless @valid_modules.include?(item[0..-4])
    end
  end

end

现在,在您的控制器中,您只需调用valid_modules对象上的Job即可返回数组。 例如:

job = Job.new
job.valid_modules

答案 1 :(得分:0)

# in config/initializers/api_modules.rb
module ApiModules
  def self.modules
    # the Dir[""] glob syntax here I believe exclude dot directories
    # but I still like the Array#include? syntax here for your exclusions list
    # you may need to massage the strings of your file list to be more appropriate to your case
    @modules ||= Dir["lib/*"].select{|f| !["resource.rb"].include?(f) } 
  end
end

#app/models/job.rb
validates :api, presence: true, :inclusion => { :in => ApiModules.modules}