如何将选项哈希传递给ruby中的模块?

时间:2014-01-27 11:27:17

标签: ruby-on-rails ruby module gem activesupport

实际上,我想配置我的宝石。

require "foo/version"
require "foo/bar"
module Foo
end

require 'securerandom'
require 'active_support'
module Foo
  module Bar
    extend ActiveSupport::Concern

    included do
      include ActiveModel::SecurePassword

      # I would to change this line to something like
      # has_secure_password validations: (validate? true : false)
      has_secure_password validations: true
    end

    module ClassMethods
    end

    extend ClassMethods
  end
end

我想从模型中加载我的宝石,例如:

class Admin < ActiveRecord::Base
  foo_bar validate: false
end

但我不知道Ruby的习惯是什么样的。怎么能实现这个目标?

1 个答案:

答案 0 :(得分:3)

您需要在模块中定义类方法foo_bar,它将接受哈希并相应地运行。例如,您可以这样做:

module Foo
  module Bar
    extend ActiveSupport::Concern

    included do
      include ActiveModel::SecurePassword
    end

    module ClassMethods
      def foo_bar(options)
        has_secure_password validations: options[:validate]
      end
    end

    extend ClassMethods
  end
end